https://www.cnblogs.com/amesy/p/8067583.html
python线程开发使用标准库threading.
thread类
def init(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)
target: 线程调用的对象,就是目标函数.
name: 为线程起个名字.
args: 为目标函数传递实参, 元组.
(如果只有一个参数,就应该写成args=(flag,)或者args=([flag]),否则会报错)
kwargs: 为目标函数关键字传参, 字典.
线程启动
import threading
def worker():
print("I'm working")
print("Finished")
t = threading.Thread(target=worker, name='worker') # 线程对象.
t.start()
通过threading.Thread创建一个线程对象,target是目标函数,name可以指定名称.
但是线程没有启动,需要调用start方法.
线程会执行函数,是因为线程中就是执行代码的,而最简单的封装就是函数,所以还是函数调用.
函数执行完,线程也会随之退出.
如果不让线程退出,或者让线程一直工作: 函数内部使用while循环.
线程传参和函数传参没什么区别,本质上就是函数传参.
import threading
import time
def add(x, y):
print('{} + {} = {}'.format(x, y, x + y, threading.current_thread()))
thread1 = threading.Thread(target=add, name='add', args=(4, 5)) # 线程对象.
thread1.start() # 启动.
time.sleep(2)
thread2 = threading.Thread(target=add, name='add',args=(5, ), kwargs={'y': 4}) # 线程对象.
thread2.start() # 启动.
time.sleep(2)
thread3 = threading.Thread(target=add, name='add', kwargs={'x': 4, 'y': 5}) # 线程对象.
thread3.start() # 启动.