本博文将从单线程、子函数中使用多线程和main中使用多线程进行示例代码演示。
1、单线程
示例代码:
import time
from queue import Queue
def task_func(queue):
while queue.qsize() > 0:
x = queue.get()
print(f"num: {x}")
time.sleep(0.1)
def single_thead():
queue = Queue()
for i in range(100):
queue.put(i)
task_func(queue)
if __name__ == '__main__':
start_time = time.time()
single_thead()
print("主程序执行结束!")
print("程序执行耗时:", time.time() - start_time)
运行结果:
2、子函数使用多线程
示例代码:
import time
import threading
from queue import Queue
def task_func(queue):
while queue.qsize() > 0:
x = queue.get()
print(f"num: {x}")
time.sleep(0.1)
def multi_thead():
queue = Queue()
for i in range(100):
queue.put(i)
thread_list = []
for i in range(5):
thread = threading.Thread(target=task_func, args=(queue, ))
thread.start()
thread_list.append(thread)
for thread in thread_list:
thread.join()
if __name__ == '__main__':
start_time = time.time()
multi_thead()
print("主程序执行结束!")
print("程序执行耗时:", time.time() - start_time)
运行结果:
3、main主函数中使用多线程
示例代码:
import time
import threading
from queue import Queue
def task_func():
global queue
while queue.qsize() > 0:
x = queue.get()
print(f"num: {x}")
time.sleep(0.1)
if __name__ == '__main__':
start_time = time.time()
queue = Queue()
for i in range(100):
queue.put(i)
thread_list = []
for i in range(5):
thread = threading.Thread(target=task_func)
thread.start()
thread_list.append(thread)
for thread in thread_list:
thread.join()
print("主程序执行结束!")
print("程序执行耗时:", time.time() - start_time)
运行结果:
综上所述:在mian主函数中使用多线程和在子函数中使用多线程效果是类似的。