方法一:threading.Thread
1.1 原理
Python多线程编程(一):threading 模块 Thread 类的用法详解
https://blog.csdn.net/briblue/article/details/85101144
1.2 代码
import threadingimport timeexitFlag = 0class myThread(threading.Thread):def __init__(self, threadID, name, delay):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.delay = delaydef run(self):print("开始线程:" + self.name)print_time(self.name, self.delay, 5)print("退出线程:" + self.name)def print_time(threadName, delay, counter):while counter:if exitFlag:threadName.exit()time.sleep(delay)print("%s: %s" % (threadName, time.ctime(time.time())))counter -= 1# 创建新线程thread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# 开启新线程thread1.start()thread2.start()thread1.join()thread2.join()print("退出主线程")
1.3 输出:
开始线程:Thread-1开始线程:Thread-2Thread-1: Tue Feb 8 21:22:51 2022Thread-2: Tue Feb 8 21:22:52 2022Thread-1: Tue Feb 8 21:22:52 2022Thread-1: Tue Feb 8 21:22:53 2022Thread-2: Tue Feb 8 21:22:54 2022Thread-1: Tue Feb 8 21:22:54 2022Thread-1: Tue Feb 8 21:22:55 2022
方法二:multiprocessing.dummy
2.1 参考资料
一行 Python 代码实现并行
https://mp.weixin.qq.com/s/akNhoFW4rF3g1OecGprGjQ
2.2 代码
import urllib.requestfrom multiprocessing.dummy import Pool as ThreadPoolfrom functools import wrapsimport timedef func_timer(function):'''用装饰器实现函数计时:param function: 需要计时的函数:return: None'''@wraps(function)def function_timer(*args, **kwargs):t0 = time.time()result = function(*args, **kwargs)t1 = time.time()print('[Function: {name} finished, spent time: {time:.2f}s]'.format(name=function.__name__, time=t1 - t0))return resultreturn function_timerurls = ['https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com','https://www.baidu.com',# etc..]@func_timerdef singleThread():results = []for url in urls:result = urllib.request.urlopen(url)results.append(result)print('Thread-single')@func_timerdef pool(n):pool = ThreadPool(n)# Open the urls in their own threads# and return the resultsresults = pool.map(urllib.request.urlopen, urls)print('Thread-%s' % str(n))if __name__ == '__main__':singleThread()pool(4)pool(8)pool(12)
2.3 输出
Thread-single[Function: singleThread finished, spent time: 1.80s]Thread-4[Function: pool finished, spent time: 0.57s]Thread-8[Function: pool finished, spent time: 0.27s]Thread-12[Function: pool finished, spent time: 0.24s]
