Python的條件鎖與事件共享詳解
1:事件機(jī)制共享隊(duì)列:
利用消息機(jī)制在兩個(gè)隊(duì)列中,通過傳遞消息,實(shí)現(xiàn)可以控制的生產(chǎn)者消費(fèi)者問題
要求:readthread讀時(shí),writethread不能寫;writethread寫時(shí),readthread不能讀。
基本方法 時(shí)間類(Event)
set:設(shè)置事件。將標(biāo)志位設(shè)為True。
wait:等待事件。會將當(dāng)前線程阻塞,直到標(biāo)志位變?yōu)門rue。
clear:清除事件。將標(biāo)志位設(shè)為False。
set() clear() 函數(shù)的交替執(zhí)行 也就是消息傳遞的本質(zhì)
模版:
基本code
# 事件消息機(jī)制
import queue
import threading
import random
from threading import Event
from threading import Thread
class WriteThread(Thread):
def __init__(self,q,wt,rt):
super().__init__();
self.queue=q;
self.rt=rt;
self.wt=wt;
def run(self):
self.rt.set()
self.wt.wait();
self.wt.clear();
class ReadThread(Thread):
def __init__(self,q,wt,rt):
super().__init__();
self.queue=q;
self.rt=rt;
self.wt=wt;
def run(self):
while True:
self.rt.wait();
self.wt.wait();
self.wt.clear()
參考代碼:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 20:10:10 2019
@author: DGW-PC
"""
# 事件消息機(jī)制
import queue
import threading
import random
from threading import Event
from threading import Thread
class WriteThread(Thread):
def __init__(self,q,wt,rt):
super().__init__();
self.queue=q;
self.rt=rt;
self.wt=wt;
def run(self):
data=[random.randint(1,100) for _ in range(0,10)];
self.queue.put(data);
print("WriteThread寫隊(duì)列:",data);
self.rt.set(); # 發(fā)送讀事件
print("WriteThread通知讀");
print("WriteThread等待寫");
self.wt.wait();
print("WriteThread收到寫事件");
self.wt.clear();
class ReadThread(Thread):
def __init__(self,q,wt,rt):
super().__init__();
self.queue=q;
self.rt=rt;
self.wt=wt;
def run(self):
while True:
self.rt.wait();# 等待寫事件 帶來
print("ReadThread 收到讀事件");
print("ReadThread 開始讀{0}".format(self.queue.get()));
print("ReadThread 發(fā)送寫事件");
self.wt.set();
self.rt.clear();
q=queue.Queue();
rt=Event();
wt=Event();
writethread=WriteThread(q,wt,rt); # 實(shí)例化對象的
readthread=ReadThread(q,wt,rt); # 實(shí)例化對象的
writethread.start();
readthread.start();
2:條件鎖同步生產(chǎn)者消費(fèi)者
作用: 在保護(hù)互斥資源的基礎(chǔ)上,增加了條件判斷的機(jī)制
即為使用wait() 函數(shù) 判斷不滿足當(dāng)前條件的基礎(chǔ)上,讓當(dāng)前線程的阻塞。
其他線程如果生成了滿足了條件的資源 使用notify() notifyALl() 函數(shù)將刮起線程喚醒。
使用了 threading 的Condition 類
acquire() : 鎖住當(dāng)前資源
relarse() :釋放當(dāng)前鎖住的資源
wait:掛起當(dāng)前線程, 等待喚起 。
• notify:喚起被 wait 函數(shù)掛起的線程 。
• notif計(jì)All:喚起所有線程,防止線程永遠(yuǎn)處于沉默狀態(tài) 。
模版:
基本code
from threading import Thread
from threading import Condition
import random
import time
lock=Condition(); # 聲明條件鎖
flag=0;
def cnsumer():
lock.acquire();
while flag==0:
lock.wait();
業(yè)務(wù)代碼---
lock.relarse();
def product():
lock.acquire();
釋放鎖之前對控制變量進(jìn)行操作,數(shù)據(jù)的操作控制 可以作為全局變量來鎖定
lock.notifyALl();
lock.relarse();
參考代碼code:
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 21:40:41 2019
@author: DGW-PC
"""
# 條件鎖生產(chǎn)者消費(fèi)者
from threading import Thread
from threading import Condition
import random
import time
flag=0; # 聲明控制標(biāo)志
goods=0; # 事物表示
lock=Condition();
def consumer(x):
global flag;
global goods;
lock.acquire(); # 取得鎖
while flag==0: # 便于多次進(jìn)行消費(fèi)
print("consumer %d進(jìn)入等待" % x);
lock.wait();
print("consumer {0}:消費(fèi)了{(lán)1}".format(x,goods));# format 次序從0開始
flag-=1;
lock.release(); #釋放鎖
def product(x):
global flag;
global goods;
time.sleep(3);
lock.acquire();
goods=random.randint(1,1000);
print("product {0} 產(chǎn)生了{(lán)1}".format(x,goods));
flag+=1;
lock.notifyAll();
lock.release();
threads=[];
for i in range(0,2):
t1=Thread(target=consumer,args=(i,));
t2=Thread(target=product,args=(i,));
t1.start();
t2.start();
threads.append(t1);
threads.append(t2);
for x in threads:
x.join();
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python實(shí)現(xiàn)賬號密碼輸錯(cuò)三次即鎖定功能簡單示例
- 對Python多線程讀寫文件加鎖的實(shí)例詳解
- Python實(shí)現(xiàn)的redis分布式鎖功能示例
- python3.0 模擬用戶登錄,三次錯(cuò)誤鎖定的實(shí)例
- Python使用文件鎖實(shí)現(xiàn)進(jìn)程間同步功能【基于fcntl模塊】
- 淺談Python 多進(jìn)程默認(rèn)不能共享全局變量的問題
- 基于python的多進(jìn)程共享變量正確打開方式
- Python multiprocessing.Manager介紹和實(shí)例(進(jìn)程間共享數(shù)據(jù))
相關(guān)文章
conda與jupyter notebook kernel核環(huán)境不一致的問題解決
本文記錄在使用conda時(shí)候出現(xiàn)的問題,jupter notebook中的環(huán)境不一致導(dǎo)致的,具有一定的參考價(jià)值,感興趣的可以了解一下2023-05-05
python3+pyqt5+itchat微信定時(shí)發(fā)送消息的方法
今天小編就為大家分享一篇python3+pyqt5+itchat微信定時(shí)發(fā)送消息的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02
Pytorch中的廣播機(jī)制詳解(Broadcast)
這篇文章主要介紹了Pytorch中的廣播機(jī)制詳解(Broadcast),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
matplotlib繪制鼠標(biāo)的十字光標(biāo)的實(shí)現(xiàn)(自定義方式,官方實(shí)例)
這篇文章主要介紹了matplotlib繪制鼠標(biāo)的十字光標(biāo)(自定義方式,官方實(shí)例),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Python進(jìn)行數(shù)據(jù)提取的方法總結(jié)
數(shù)據(jù)提取是分析師日常工作中經(jīng)常遇到的需求。如某個(gè)用戶的貸款金額,某個(gè)月或季度的利息總收入,某個(gè)特定時(shí)間段的貸款金額和筆數(shù),大于5000元的貸款數(shù)量等等。本篇文章介紹如何通過python按特定的維度或條件對數(shù)據(jù)進(jìn)行提取,完成數(shù)據(jù)提取需求。2016-08-08
Python *args和**kwargs用法實(shí)例解析
這篇文章主要介紹了Python *args和**kwargs用法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03

