importthreadingimportloggingclassMyThreadWithArgs(threading.Thread):def__init__(self,group=None,target=None,name=None,args=(),kwargs=None,*,daemon=None):super().__init__(group=group,target=target,name=name,daemon=daemon)self.args=argsself.kwargs=kwargsdefrun(self):logging.debug('running with %s and %s',self.args,self.kwargs)logging.basicConfig(level=logging.DEBUG,format='(%(threadName)-10s) %(message)s',)foriinrange(5):t=MyThreadWithArgs(args=(i,),kwargs={'a':'A','b':'B'})t.start()

importloggingimportthreadingimporttimedefwait_for_event(e):"""Wait for the event to be set before doing anything"""logging.debug('wait_for_event starting')event_is_set=e.wait()logging.debug('event set: %s',event_is_set)defwait_for_event_timeout(e,t):"""Wait t seconds and then timeout"""whilenote.is_set():logging.debug('wait_for_event_timeout starting')event_is_set=e.wait(t)logging.debug('event set: %s',event_is_set)ifevent_is_set:logging.debug('processing event')else:logging.debug('doing other work')logging.basicConfig(level=logging.DEBUG,format='(%(threadName)-10s) %(message)s',)e=threading.Event()t1=threading.Thread(name='block',target=wait_for_event,args=(e,),)t1.start()t2=threading.Thread(name='nonblock',target=wait_for_event_timeout,args=(e,2),)t2.start()logging.debug('Waiting before calling Event.set()')time.sleep(0.3)e.set()logging.debug('Event is set')

importloggingimportthreadingimporttimedefconsumer(cond):"""wait for the condition and use the resource"""logging.debug('Starting consumer thread')withcond:cond.wait()logging.debug('Resource is available to consumer')defproducer(cond):"""set up the resource to be used by the consumer"""logging.debug('Starting producer thread')withcond:logging.debug('Making resource available')cond.notifyAll()logging.basicConfig(level=logging.DEBUG,format='%(asctime)s (%(threadName)-2s) %(message)s',)condition=threading.Condition()c1=threading.Thread(name='c1',target=consumer,args=(condition,))c2=threading.Thread(name='c2',target=consumer,args=(condition,))p=threading.Thread(name='p',target=producer,args=(condition,))c1.start()time.sleep(0.2)c2.start()time.sleep(0.2)p.start()