目录
一、python 启用多线程:
from therading import Thread
t = Thread(target=task1, args=())
t.start()
例如:
def task1():
for i in range(5):
time.sleep(1)
print('task 1')
def task2(string):
for i in range(5):
time.sleep(1)
print(string)
if __name__ == '__main__':
print('主线程')
t = Thread(target=task1, args=())
t.start()
t2 = Thread(target=task2, args=('task2',))
t2.start()
print("主线程结束")
输出结果为:
注意,带参数的api使用args=()传入参数,并且注意后面要加一个逗号,否则会提示错误
positional argument but 5 were given
二、任务队列:
将要操作的任务添加到一个队列当中(这些操作串行运行),在另一个线程中启动任务队列。
from threading import Thread
import time
import queue
def task1():
for i in range(5):
time.sleep(1)
print('task 1')
def task2(string):
for i in range(5):
time.sleep(1)
print(string)
def opt_que():
op_que = queue.Queue()
op_que.put(task1())
op_que.put(task2('task2'))
print(op_que.qsize())
if __name__ == '__main__':
print('主线程')
t = Thread(target=opt_que,)
t.start()
print("主线程结束")
输出结果为: