import time
import queue
import threading
class LogQueue( queue.Queue ) :
def __init__ ( self , lock) :
self ._lock = lock
self .writes = 0
super ( self .__class__, self ) .__init__ ( )
def _dump( self ) :
print ( '\n =======' )
with self ._lock:
while not self .empty ( ) :
print ( 'GOT' , self .get ( ) )
time .sleep ( 0.5 )
print ( '=======\n ' )
def put( self , *args, **kwargs) :
super ( self .__class__, self ) .put ( *args, **kwargs)
self .writes += 1
if self .writes == 5 :
self .writes = 0
self ._dump( )
# def __del__(self):
# self._log.close()
def writer( lock, log, condition) :
i = 0
while True :
if i == 15 :
return
if condition( i) :
with lock:
log.put ( i)
print ( 'PUT' , i)
time .sleep ( 0.1 )
i += 1
lock = threading .RLock ( )
log = LogQueue( lock)
threading .Thread ( target= writer, args= ( lock, log, lambda i: i % 2 == 0 ) ) .start ( )
threading .Thread ( target= writer, args= ( lock, log, lambda i: i % 2 != 0 ) ) .start ( )
aW1wb3J0IHRpbWUKCmltcG9ydCBxdWV1ZQppbXBvcnQgdGhyZWFkaW5nCgoKY2xhc3MgTG9nUXVldWUocXVldWUuUXVldWUpOgoKICAgIGRlZiBfX2luaXRfXyhzZWxmLCBsb2NrKToKICAgICAgICBzZWxmLl9sb2NrID0gbG9jawogICAgICAgIHNlbGYud3JpdGVzID0gMAoKICAgICAgICBzdXBlcihzZWxmLl9fY2xhc3NfXywgc2VsZikuX19pbml0X18oKQoKICAgIGRlZiBfZHVtcChzZWxmKToKICAgICAgICBwcmludCgnXG49PT09PT09JykKICAgICAgICB3aXRoIHNlbGYuX2xvY2s6CiAgICAgICAgICAgIHdoaWxlIG5vdCBzZWxmLmVtcHR5KCk6CiAgICAgICAgICAgICAgICBwcmludCgnR09UJywgc2VsZi5nZXQoKSkKICAgICAgICAgICAgdGltZS5zbGVlcCgwLjUpCiAgICAgICAgcHJpbnQoJz09PT09PT1cbicpCgogICAgZGVmIHB1dChzZWxmLCAqYXJncywgKiprd2FyZ3MpOgogICAgICAgIHN1cGVyKHNlbGYuX19jbGFzc19fLCBzZWxmKS5wdXQoKmFyZ3MsICoqa3dhcmdzKQoKICAgICAgICBzZWxmLndyaXRlcyArPSAxCiAgICAgICAgaWYgc2VsZi53cml0ZXMgPT0gNToKICAgICAgICAgICAgc2VsZi53cml0ZXMgPSAwCiAgICAgICAgICAgIHNlbGYuX2R1bXAoKQoKICAgICMgZGVmIF9fZGVsX18oc2VsZik6CiAgICAjICAgICBzZWxmLl9sb2cuY2xvc2UoKQoKCmRlZiB3cml0ZXIobG9jaywgbG9nLCBjb25kaXRpb24pOgogICAgaSA9IDAKICAgIHdoaWxlIFRydWU6CiAgICAgICAgaWYgaSA9PSAxNToKICAgICAgICAgICAgcmV0dXJuCgogICAgICAgIGlmIGNvbmRpdGlvbihpKToKICAgICAgICAgICAgd2l0aCBsb2NrOgogICAgICAgICAgICAgICAgbG9nLnB1dChpKQogICAgICAgICAgICAgICAgcHJpbnQoJ1BVVCcsIGkpCiAgICAgICAgdGltZS5zbGVlcCgwLjEpCiAgICAgICAgaSArPSAxCgoKbG9jayA9IHRocmVhZGluZy5STG9jaygpCmxvZyA9IExvZ1F1ZXVlKGxvY2spCgp0aHJlYWRpbmcuVGhyZWFkKHRhcmdldD13cml0ZXIsIGFyZ3M9KGxvY2ssIGxvZywgbGFtYmRhIGk6IGkgJSAyID09IDApKS5zdGFydCgpCnRocmVhZGluZy5UaHJlYWQodGFyZ2V0PXdyaXRlciwgYXJncz0obG9jaywgbG9nLCBsYW1iZGEgaTogaSAlIDIgIT0gMCkpLnN0YXJ0KCkK