1、多线程使用案例
import time import threading def coding(): for x in range(0,3): print("正在写代码......") print(threading.current_thread()) time.sleep(1) def drawing(): for x in range(3): print("正在画图.......") print(threading.current_thread()) time.sleep(1) if __name__ == '__main__': t1 = threading.Thread(target=coding) t2 = threading.Thread(target=drawing) t1.start() t2.start() print(threading.enumerate())
2、线程锁
import threading import time import random '''线程锁''' VALUE = 0 gLock = threading.Lock() def add_value(): global VALUE gLock.acquire() for x in range(1000000): VALUE = VALUE + 1 gLock.release() print(VALUE) if __name__ == '__main__': for i in range(2): t = threading.Thread(target=add_value) t.start()
3、生产者/消费者模型Lock
# 生产者/消费者模型Lock g_Money = 1000 g_TotalTimes = 10 g_Times =0 g_Lock = threading.Lock() class Producer(threading.Thread): def run(self): global g_Money global g_Times while True: g_Lock.acquire() if g_Times>g_TotalTimes: print("生产结束!!") g_Lock.release() break else: g_Times += 1 money = random.randint(10,1000) g_Money += money print("生产者线程{}生产了{}钱,余额为:{}".format(threading.current_thread(),money,g_Money)) g_Lock.release() time.sleep(1) class Consumer(threading.Thread): def run(self): global g_Money global g_Times while True: money = random.randint(10,1000) g_Lock.acquire() if money > g_Money: if g_Times > g_TotalTimes: print("消费不起了,兄弟") g_Lock.release() break else: print("对不起,余额不足!!!") g_Lock.release() else: g_Money -= money print("消费者线程{}消费了{}钱,余额为:{}".format(threading.current_thread(), money, g_Money)) g_Lock.release() time.sleep(1) if __name__ == '__main__': for i in range(3): consumer = Consumer(name="消费者线程{}".format(i)) consumer.start() for j in range(5): producer = Producer(name="生产者线程{}".format(j)) producer.start()
4、生产者/消费者模型Condition
import time,random import threading g_Money = 1000 g_TotalTimes = 10 g_Times =0 g_Condition = threading.Condition() class Producer(threading.Thread): def run(self): global g_Money global g_Times while True: g_Condition.acquire() if g_Times>g_TotalTimes: print("生产结束!!") g_Condition.release() break else: g_Times += 1 money = random.randint(10,1000) g_Money += money print("生产者线程{}生产了{}钱,余额为:{}".format(threading.current_thread(),money,g_Money)) g_Condition.notify_all() g_Condition.release() time.sleep(1) class Consumer(threading.Thread): def run(self): global g_Money global g_Times while True: money = random.randint(10,1000) g_Condition.acquire() while g_Money < money: if g_Times>g_TotalTimes: g_Condition.release() return else: print("{}准备消费{}元,余额为{}元,余额不足!!!".format(threading.currentThread,money,g_Money)) g_Condition.wait() g_Money -= money print("{}消费了{}元,还剩{}元".format(threading.currentThread,money,g_Money)) g_Condition.release() time.sleep(1) if __name__ == '__main__': for i in range(3): consumer = Consumer(name="消费者线程{}".format(i)) consumer.start() for j in range(5): producer = Producer(name="生产者线程{}".format(j)) producer.start()