0
点赞
收藏
分享

微信扫一扫

python多线程的使用

沐之轻语 2022-02-14 阅读 65

一个程序为一个进程一个进程包括一个或多个线程,python多线程可以理解为多个线程同时干不同的事情。

Python3 线程中常用的两个模块为:

  • _thread
  • threading(推荐)

用多线程与没用多线程的区别

以下两个实例中他们都是调用的同一个函数,其中第一个实例没有用多线程,第二个调用 _thread 模块中的start_new_thread()函数来产生新线程

第一个实例:

# 第一个实例没用多线程
import time       # 导入模块

def print_time(threadName, delay):     # 定义函数 (名字,延时)
   count = 1                    # 定义累加初始值
   while count <= 5:            # 循环五次
      time.sleep(delay)         # 延时
      count += 1                # 累加
      print("%s: %s" % (threadName, time.ctime(time.time())))  # 格式化

print_time('thread_1',2)      # 第一次调用函数用时 2*5=10
print_time('thread_2',4)      # 第二次调用函数用时 4*5=20

输出:

 第二个实例:

# 第二个实例用了多线程

import _thread
import time

dict_time = {}      # 定义一个字典用来存储进程开始时间与结束时间
# 为线程定义一个函数
def print_time( threadName, delay):
    count = 1
    while count <= 5:
        if threadName == 'Thread-1' and count == 1: # 线程1第一个循环开始
            start_time = time.time()    # 开始时间
            print('开始时间',start_time)
            dict_time['start_time'] = start_time    # 将开始时间追加到字典
        time.sleep(delay)       # 延时
        print ("%s: %s" % ( threadName, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ))  # 格式化
        if threadName == 'Thread-2' and count == 5: # 线程2最后一个循环结束
            global ent_time
            ent_time = time.time()      # 结束时间
            print('结束时间',ent_time)
            dict_time['ent_time'] = ent_time
            print('程序用时:',dict_time['ent_time']-dict_time['start_time'])
        count += 1  # 累计


# 创建两个线程
try:
    _thread.start_new_thread( print_time, ("Thread-1", 2, ) )    # 线程1用时:2*5=10s
    _thread.start_new_thread( print_time, ("Thread-2", 4, ) )    # 线程2用时:4*5=20s
except:
    print ("Error: 无法启动线程")

while True:
    pass

输出:

 小结:

可以通过上面这两个实例的输出看出来,他们做了相同的事情。第一个实例没有用多线程,他们执行的时间为30秒(10+20),第二个实例用到了多线程只花了30秒(10<20)。不用多线程调用两个函数是执行完一个再执行下一个的,而多线程是同时执行的,因此一共执行的时间是取最多的那个,由此可见python多线程可以大大提高代码执行的效率。

举报

相关推荐

0 条评论