Python 35 线程(2)线程特性、守护线程、线程互斥锁

时间:2023-12-05 23:31:56

一:线程特性介绍

from threading import Thread
import time n=100
def task():
global n
n=0 if __name__ == '__main__':
t=Thread(target=task)
t.start()
t.join()
print('主',n) from threading import Thread
import time,os def task():
print('%s is running' %os.getpid()) if __name__ == '__main__':
t=Thread(target=task)
t.start()
print('主',os.getpid())
from threading import Thread,active_count,current_thread
import time,os def task():
print('%s is running' %current_thread().name)
time.sleep(2) if __name__ == '__main__':
t=Thread(target=task,)
t.start()
# t.join()
# print('主',active_count())
print('主',current_thread().name)

二:守护线程

from threading import Thread
import time def task(name):
print('%s is running' %name)
time.sleep(2)
print('%s is done' %name) if __name__ == '__main__':
t=Thread(target=task,args=('线程1',))
t.daemon=True
t.start()
print('主')
from threading import Thread
from multiprocessing import Process
import time
def foo():
print(123)
time.sleep(1)
print("end123") def bar():
print(456)
time.sleep(3)
print("end456") if __name__ == '__main__':
t1=Thread(target=foo)
t2=Thread(target=bar) # t1=Process(target=foo)
# t2=Process(target=bar)
t1.daemon=True
t1.start()
t2.start()
print("main-------")

三:线程互斥锁

from threading import Thread,Lock
import time mutex=Lock()
n=100
def task():
global n
mutex.acquire()
temp=n
time.sleep(0.1)
n=temp-1
mutex.release() if __name__ == '__main__':
t_l=[]
for i in range(100):
t=Thread(target=task)
t_l.append(t)
t.start() for t in t_l:
t.join()
print(n)