1.執行緒間的通信方式
1.共享全域變數
2.執行緒佇列(queue)
3.信號量(Semaphore)
2.共享全域變數進行通信
from threading import Thread import time g_nums = [11,22,33] def work1(nums): nums.append(44) print("----in work1---",nums) def work2(nums): #延時一會,保證t1執行緒中的事情做完 time.sleep(1) print("----in work2---",nums) t1 = Thread(target=work1, args=(g_nums,)) t1.start() t2 = Thread(target=work2, args=(g_nums,)) t2.start()
3.共享全域變數的資源競爭
# 多個執行緒同時對同一個全域變數操作,會出現資源競爭問題,從而資料結果會不正確 import threading import time g_num = 0 def work1(num): global g_num for i in range(num): g_num += 1 print("----in work1, g_num is %d---" % g_num) def work2(num): global g_num for i in range(num): g_num += 1 print("----in work2, g_num is %d---" % g_num) print("---執行緒創建之前g_num is %d---" % g_num) t1 = threading.Thread(target=work1, args=(1000000,)) t1.start() t2 = threading.Thread(target=work2, args=(1000000,)) t2.start() while len(threading.enumerate()) != 1: time.sleep(1) print("2個執行緒對同一個全域變數操作之后的最終結果是:%s" % g_num)
4.執行緒佇列queue.Queue-生產者消費者模式
from threading import Thread import queue from time import sleep # 生產者 class Producer(Thread): def run(self): count = 0 while True: if q.qsize() < 50: for i in range(3): count += 1 msg = "產品%d" % count # 將產品放入佇列 q.put(msg) # print("生產了: %s 還有%s個" % (msg, q.qsize())) sleep(1) # 消費者 class Customer(Thread): def run(self): while True: if q.qsize() > 20: for i in range(2): msg = q.get() # 從倉庫中拿貨 print("消耗了: %s 還有%s個" % (msg, q.qsize())) sleep(1) def main(): # 創建一個佇列倉庫 global q q = queue.Queue() # 創建2個生產 for i in range(2): p = Producer() p.start() # 創建3個消費 for i in range(3): c = Customer() c.start() if __name__ == "__main__": main() """執行結果 消耗了: 產品1 還有20個 消耗了: 產品2 還有22個 消耗了: 產品3 還有24個 消耗了: 產品1 還有23個 消耗了: 產品2 還有25個 消耗了: 產品3 還有24個 消耗了: 產品4 還有23個 消耗了: 產品5 還有22個 """
5.執行緒佇列-先進先出佇列,后進先出佇列,優先級佇列
from multiprocessing import Queue # 是用于多行程的佇列,就是專門用來做行程間通信(IPC) import queue # 是用于同一行程內的佇列,不能做多行程之間的通信 q = queue.Queue() # 先進先出 q.put(1) q.put(2) q.put(3) print(q.get()) print(q.get()) q = queue.LifoQueue() # 后進先出的佇列 q.put(1) q.put(2) q.put(3) print(q.get()) q = queue.PriorityQueue() # 優先級佇列,put()方法接收的是一個元組(),第一個位置是優先級,第二個位置是資料 # 優先級如果是數字,直接比較數值 # 如果是字串,是按照 ASCII 碼比較的,當ASCII碼相同時,會按照先進先出的原則 q.put((1, 'abc')) q.put((5, 'qwe')) q.put((-5, 'zxc')) print(q.get()) print(q.get())
6.信號量-Semaphore
from threading import Semaphore from threading import Thread import time def func(sem, i): sem.acquire() print('第%s個人進入屋子' % i) time.sleep(2) print('第%s個人離開屋子' % i) sem.release() sem = Semaphore(5) for i in range(20): t = Thread(target=func, args=(sem, i)) t.start()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/20969.html
標籤:Python
上一篇:口紅送什么色號,這是一個難題,爬取口紅資料,希望對你有所幫助
下一篇:0826一些python基礎練習
