知道代码(持续更新)
1.科学家吃面代码
此程序因互斥锁会产生死锁现象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from threading import Thread, Lock import time noodle_lock = Lock() fork_lock = Lock() def eat1(name): noodle_lock.acquire() print('%s在eat1拿到了面'%name) fork_lock.acquire() print('%s在eat1拿到了叉子'%name) print('%s在eat1吃面'%name) time.sleep(2) fork_lock.release() noodle_lock.release() def eat2(name): fork_lock.acquire() print('%s在eat2拿到了叉子'%name) noodle_lock.acquire() print('%s在eat2拿到了面'%name) print('%s在eat2在吃面'%name) time.sleep(2) fork_lock.release() noodle_lock.release() eat_lst = ['alex', 'wusir', '太白', 'yuan'] for name in eat_lst: Thread(target=eat1, args=(name,)).start() Thread(target=eat2, args=(name,)).start()
可以通过递归锁(RLock)或改变代码逻辑解决死锁现象
2.多进程起socket
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#服务器端 import socket from multiprocessing import Process def fanc(conn, num): try: while True: msg_s = '你好%s'% num conn.send(msg_s.encode('utf-8')) print(conn.recv(1024).decode('utf-8')) finally: conn.close() if __name__ == '__main__': try: sk = socket.socket() sk.bind(('127.0.0.1', 9090)) sk.listen() num = 0 while True: conn, addr = sk.accept() num += 1 p = Process(target=fanc, args=(conn,num)) p.start() finally: sk.close() #客户端 import os import time import socket sk = socket.socket() sk.connect(('127.0.0.1', 9090)) while True: print(sk.recv(1024).decode('utf-8')) sk.send(str(os.getpid()).encode('utf-8'))
多线程与其相似
3.进程multiprocessing模块中事件Event红绿灯模型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 红绿灯模型 # 控制交通灯的进程 import time import random from multiprocessing import Event,Process def traffic_light(e): print('\033[1;31m 红灯亮\033[0m') while True: time.sleep(2) if e.is_set(): print('\033[1;31m 红灯亮\033[0m') e.clear() else: print('\033[1;32m 绿灯亮\033[0m') e.set() # 车 等或者通过 def car(id,e): if not e.is_set(): print('car %s 等待' % id) e.wait() print('car %s 通过'%id) def police_car(id,e): if not e.is_set(): e.wait(timeout = 0.5) print('police car %s 通过' % id) # 主进程 启动交通控制灯 启动车的进程 if __name__ == '__main__': e = Event() p = Process(target=traffic_light,args=(e,)) p.start() car_lst = [car,police_car] for i in range(20): p = Process(target=random.choice(car_lst), args=(i,e)) p.start() time.sleep(random.randrange(0,3,2))