守护线程
import timefrom threading import Threaddef func1(): while True: print(‘*‘*10) time.sleep(1)def func2(): print(‘in func2‘) time.sleep(5) t = Thread(target=func1,)t.daemon = Truet.start()t2 = Thread(target=func2,)t2.start()t2.join() #加join后会等待func2结束后在打印print(‘主线程‘) # 守护进程随着主进程代码的执行结束而结束 # 守护线程会在主线程结束之后等待其他子线程的结束才结束 # 主进程在执行完自己的代码之后不会立即结束 而是等待子进程结束之后 回收子进程的资源# import time# from multiprocessing import Process# def func():# time.sleep(5)## if __name__ == ‘__main__‘:# Process(target=func).start()
线程锁
为什么Cpython自带GIL锁还出现死锁,因为是对线程GIL锁,避免不了时间片轮转带来数据不安全
import timefrom threading import Lock,Thread# Lock 互斥锁(只有一个钥匙) # def func(lock):# global n# lock.acquire()# temp = n# time.sleep(0.2)# n = temp - 1# lock.release()## n = 10# t_lst = []# lock = Lock()# for i in range(10):# t = Thread(target=func,args=(lock,))# t.start()# t_lst.append(t) # for t in t_lst: t.join()# print(n) # 科学家吃面 # noodle_lock = Lock()# fork_lock = Lock()# def eat1(name):# noodle_lock.acquire()# print(‘%s拿到面条啦‘%name)# fork_lock.acquire()# print(‘%s拿到叉子了‘%name)# print(‘%s吃面‘%name)# fork_lock.release()# noodle_lock.release()## def eat2(name):# fork_lock.acquire()# print(‘%s拿到叉子了‘%name)# time.sleep(1)# noodle_lock.acquire()# print(‘%s拿到面条啦‘%name)# print(‘%s吃面‘%name)# noodle_lock.release()# fork_lock.release()## Thread(target=eat1,args=(‘alex‘,)).start() # Thread(target=eat2,args=(‘Egon‘,)).start()# Thread(target=eat1,args=(‘bossjin‘,)).start()# Thread(target=eat2,args=(‘nezha‘,)).start()执行上面代码后出现死锁阻塞 解决死锁问题 from threading import RLock # 递归锁(一串钥匙,多少根据accquire多少次) fork_lock = noodle_lock = RLock() # 一个钥匙串上的两把钥匙def eat1(name): noodle_lock.acquire() # 一把钥匙 print(‘%s拿到面条啦‘%name) fork_lock.acquire() print(‘%s拿到叉子了‘%name) print(‘%s吃面‘%name) fork_lock.release() noodle_lock.release() def eat2(name): fork_lock.acquire() print(‘%s拿到叉子了‘%name) time.sleep(1) noodle_lock.acquire() print(‘%s拿到面条啦‘%name) print(‘%s吃面‘%name) noodle_lock.release() fork_lock.release() Thread(target=eat1,args=(‘alex‘,)).start()Thread(target=eat2,args=(‘Egon‘,)).start()Thread(target=eat1,args=(‘bossjin‘,)).start()Thread(target=eat2,args=(‘nezha‘,)).start()
原文地址:https://www.cnblogs.com/mys6/p/10886510.html
时间: 2024-10-07 18:02:49