Senza che apro un nuovo post:
Vediamo se ho capito, per esempio se ho una funzione che fa il read di un file acceduta da più thread ha senso lockare giusto?
Ipotizziamo :
codice:
# -*- coding: utf-8 -*-
class Example(object):
def __init__(self, e, q):
self.e = e
self.q = q
def main(self):
Thread(target=self.thread1, args=(self.e, self.q)).start()
Thread(target=self.thread2, args=(self.e, self.q)).start()
Thread(target=self.thread3, args=(self.e, self.q)).start()
def thread1(self, e, q):
while True:
if q.empty():
print "Thread 1"
else:
try:
print q.get()
print "Size:", q.qsize()
except:
print "Size:", q.qsize()
e.clear() # For security reason
e.set()
e.wait()
sleep(1)
def thread2(self, e, q):
c = 0
while True:
print "Thread 2"
if c > 5: # and e.isSet():
try:
print "Clear"
e.clear()
except:
print "Err clear"
c += 1
sleep(5)
def thread3(self, e, q):
c = 0
while True:
print "Thread 3"
if c == 1:
q.put("Block")
c += 1
sleep(10)
if __name__ == "__main__":
from time import sleep, time
from threading import Thread, Event
from Queue import Queue
Example(q = Queue(1), e = Event()).main()
Queste righe di codice che ho scritto funzionano per "bloccare" e "sbloccare" il thread1().
Ma se volessi in qualche modo sbloccare solo 1 thread? e.clear() da come ho capito li sblocca tutti no? L'unica soluzione che mi viene in mente e sbloccarli tutti con e.clear() e poi bloccare subito quelli di cui non sono più interessato.
Grazie di tutto