• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python线程的创建和常用方法

武飞扬头像
PHP中文网
帮助27

线程的创建与使用

在Python中有很多的多线程模块,其中 threading 模块就是比较常用的。下面就来看一下如何利用 threading 创建线程以及它的常用方法。

线程的创建 -threading

线程对象的常用方法

接下里看一下线程对象中都有哪些常用的方法:

线程演示案例

单线程初始案例

演示 多线程之前 先看一下下面这个案例,运行结束后看看共计耗时多久

代码示例如下:

# coding:utf-8import timeimport random


old_lists = ['罗马假日', '怦然心动', '时空恋旅人', '天使爱美丽', '天使之城', '倒霉爱神', '爱乐之城']new_lists = []def work():
    if len(old_lists) == 0:     # 判断 old_list 的长度,如果为0 ,则表示 该列表的内容已经被删光了
        return '\'old_list\' 列表内容已经全部删除'
    old_choice_data = random.choice(old_lists)      # random 模块的 choice函数可以随机获取传入的 old_list 的元素
    old_lists.remove(old_choice_data)               # 当获取到这个随机元素之后,将该元素从 old_lists 中删除
    new_choice_data = '%s_new' % old_choice_data    # 将随机获取到的随机元素通过格式化方式重新赋值,区别于之前的元素
    new_lists.append(new_choice_data)               # 将格式化的新的随机元素添加至 new_lists 列表

    time.sleep(1)if __name__ == '__main__':
    strat_time = time.time()

    for i in range(len(old_lists)):
        work()

    if len(old_lists) ==0:
        print('\'old_lists\' 当前为:{}'.format(None))
    else:
        print(('\'old_lists\' 当前为:{}'.format(old_lists)))

    if not len(new_lists) == 0:
        print(('\'new_lists\' 当前为:{}'.format(new_lists)))
    else:
        print('\'new_lists\' 当前为:{}'.format(None))

    end_time = time.time()
    print('运行结束,累计耗时:{} 秒'.format(end_time - strat_time))

运行结果如下:


学新通技术网

从运行输出结果我们可以看到整个脚本运行共计耗时7秒,而且 new_lists 列表内的元素都经过格式化处理后加上了 _new ;不仅如此, 因为 random模块的choice函数 原因,new_lists 的内容顺序与 old_lists 也是不一样;每次运行顺序都会不一样,所以 old_lists 的顺序是无法得到保障的。


多线程演示案例

代码示例如下:

# coding:utf-8import timeimport randomimport threading


old_lists = ['罗马假日', '怦然心动', '时空恋旅人', '天使爱美丽', '天使之城', '倒霉爱神', '爱乐之城']new_lists = []def work():
    if len(old_lists) == 0:     # 判断 old_list 的长度,如果为0 ,则表示 该列表的内容已经被删光了
        return '\'old_list\' 列表内容已经全部删除'
    old_choice_data = random.choice(old_lists)      # random 模块的 choice函数可以随机获取传入的 old_list 的元素
    old_lists.remove(old_choice_data)               # 当获取到这个随机元素之后,将该元素从 old_lists 中删除
    new_choice_data = '%s_new' % old_choice_data    # 将随机获取到的随机元素通过格式化方式重新赋值,区别于之前的元素
    new_lists.append(new_choice_data)               # 将格式化的新的随机元素添加至 new_lists 列表

    time.sleep(1)if __name__ == '__main__':
    strat_time = time.time()

    print('\'old_lists\'初始长度为:{}'.format(len(old_lists)))	# 获取 old_lists 与 new_lists 最初始的长度
    print('\'new_lists\'初始长度为:{}'.format(len(new_lists)))
    thread_list = []        # 定义一个空的 thread_list 对象,用以下方添加每个线程

    for i in range(len(old_lists)):
        thread_work = threading.Thread(target=work)     # 定义一个线程实例化对象执行 work 函数,因为 work 函数没有参数所以不用传 args
        thread_list.append(thread_work)                 # 将 thread_work 添加进 thread_list
        thread_work.start()                             # 启动每一个线程

    for t in thread_list:   # 通过for循环将每一个线程进行阻塞
        t.join()

    if len(old_lists) ==0:
        print('\'old_lists\' 当前为:{}'.format(None), '当前长度为:{}'.format(len(old_lists)))
    else:
        print(('\'old_lists\' 当前为:{}'.format(old_lists)))

    if not len(new_lists) == 0:
        print('\'new_lists\' 当前长度为:{}'.format(len(new_lists)))
        print('\'new_lists\' 当前的值为:{}'.format(new_lists))
    else:
        print('\'new_lists\' 当前为:{}'.format(None))

    end_time = time.time()
    print('运行结束,累计耗时:{} 秒'.format(end_time - strat_time))

运行结果如下:


学新通技术网

从运行的结果来看,我们初始的单线程任务耗时为 7秒,在使用多线程之后,仅耗时 1秒就完成了,大大的提高了我们的运行效率。


线程的问题

通过上面的练习,我们发现线程的使用方法几乎与进程是一模一样的。它们都可以互不干扰的执行程序,也可以使得主线程的程序不需要等待子线程的任务完成之后再去执行。只不过刚刚的演示案例中我们使用了 join() 函数进行了阻塞,这里可以吧 join() 去掉,看看执行效果。

与进程一样,线程也存在着一定的问题。

  • 线程执行的函数,也同样是无法获取返回值的。
  • 当多个线程同时修改文件一样会造成被修改文件的数据错乱的错误(因为都是并发去操作一个文件,特别是在处理交易场景的时候,需要尤为注意)。

关于这些线程中存在的问题同样是可以解决的,在下一章节的 线程池与全局锁 我们会有详细的介绍。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanffcke
系列文章
更多 icon
同类精品
更多 icon
继续加载