线程是进程中执行代码的一个分支,每个执行分支(线程)要想工作执行代码需要cpu进行调度 ,也就是说线程是cpu调度的基本单位,每个进程至少都有一个线程,而这个线程就是我们通常说的主线程。
import threading
import time
def t_01(name, age):
for i in range(10):
print("线程1({}):{}今年{}岁".format(threading.current_thread(), name, age))
time.sleep(0.2)
def t_02(name, age):
for i in range(10):
print("线程2 ({}):{}今年{}岁".format(threading.current_thread(), name, age))
time.sleep(0.2)
if __name__ == '__main__':
thread_01 = threading.Thread(target=t_01, name="线程一", args=("小明",), kwargs={"age": 18})
thread_02 = threading.Thread(target=t_02, name="线程二", args=("小友",), kwargs={"age": 20})
thread_01.start()
thread_02.start()
线程默认是非守护线程,所以当主线程跑完,会等待子线程跑完,才继续运行。可以修改线程的为守护线程:
python thread_01 = threading.Thread(target=t_01, name="线程一", args=("小明",), kwargs={"age": 18},daemon=True)
thread_01.setDaemon(True)
注意:线程执行顺序是无序的,同时全局变量是共享的。所以会存在全局变量数据错误的问题。解决方法使用线程同步(join任务一,再开始,这样又不是并发)。或者使用互斥锁,对需要保护的操作进行锁定,保持同时只有一个线程在操作,注意避免死锁情况,上锁就要及时释放。
import threading
sum = 0
def t_01():
for i in range(1000000):
global sum
sum += 1
def t_02():
for i in range(1000000):
global sum
sum += 1
if __name__ == '__main__':
thread_01 = threading.Thread(target=t_01, name="线程一")
thread_02 = threading.Thread(target=t_02, name="线程二")
thread_01.start()
thread_02.start()
thread_01.join()
thread_02.join()
print("sum:{}".format(sum))
代码运行后,最后的sum值不为:2000000。所以可以适当加锁操作
import threading
sum = 0
lock = threading.Lock()
def t_01():
for i in range(1000000):
lock.acquire()
global sum
sum += 1
lock.release()
def t_02():
for i in range(1000000):
lock.acquire()
global sum
sum += 1
lock.release()
if __name__ == '__main__':
thread_01 = threading.Thread(target=t_01, name="线程一")
thread_02 = threading.Thread(target=t_02, name="线程二")
thread_01.start()
thread_02.start()
thread_01.join()
thread_02.join()
print("sum:{}".format(sum))