守护线程
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)
网友评论