关于Python的进程线程协程之threading模块(三)Event对象

来源:互联网 发布:网络的好处英文怎么写 编辑:程序博客网 时间:2024/06/08 16:32

关于Python的进程线程协程之threading模块(三)Event对象


Event对象:通用的条件变量。多个线程可以等待某个线程的发生,当事件发生后,所有的线程都会被激活。


#_*_coding:utf-8_*_import threadingfrom time import sleep, ctime"""the process that have mode of thread """_max_link = 30# A pool of thread max-linkthread_pool = []# A list for saving instantiations of threadlock_pool = []# A list for saving instantiation of Lockcount = 0# A global vardef loop(*args):    '''A function for sleep sometime s ,and make global count ++'''    _index,_lock_Semaphore,_event_sign = args    _event_sign.wait()    print "start loop %s at: " % _index, ctime()    _lock_Semaphore.acquire()    global count    count += 1    _lock_Semaphore.release()    sleep(2)    print "end loop %s at: " % _index, ctime()def Thread_Pool(*arg):    """A function that create instantiations of threading"""    _func, _LN ,_Lock,_Event_Local= arg    for i in range(_LN):        t = threading.Thread(target=_func, args=(i,_Lock,_Event_Local))#可能不能直接传列表元素,只能传列表    #    t.setDaemon(True)    #    print t.isDaemon()        thread_pool.append(t)def Thread_Start(arg):    """A function that represents a thread of control.      And by calling them instantiations ,that produced from       'threading.Thread', from list thread_pool ,      And block the main thread      """    for i in range(arg):        thread_pool[i].start()def main():    """A function of main"""    _event_obj = threading.Event()    _event_obj.clear()    _Semaphore = threading.BoundedSemaphore(5)    print "process start at: ".upper(), ctime()    Thread_Pool(loop, _max_link,_Semaphore,_event_obj)    Thread_Start(_max_link)    inp = raw_input("---$:")    if inp == "True":        _event_obj.set()    print "process end at: ".upper(), ctime(),"now count :",countif __name__ == '__main__':    main()

运行结果:


PROCESS START AT:  Fri Apr 28 17:27:08 2017---$:TruePROCESS END AT: start loop 2 at:  start loop 3 at:  Fri Apr 28 17:27:18 2017start loop 6 at:  Fri Apr 28 17:27:18 2017 start loop 4 at: Fri Apr 28 17:27:18 2017 Fri Apr 28 17:27:18 2017start loop 0 at:  now count : Fri Apr 28 17:27:18 2017start loop 7 at:  Fri Apr 28 17:27:18 2017  1······此处省略多处······end loop 28 at: end loop 26 at: end loop 27 at: end loop 5 at: end loop 29 at:      Fri Apr 28 17:27:20 2017Fri Apr 28 17:27:20 2017Fri Apr 28 17:27:20 2017Fri Apr 28 17:27:20 2017Fri Apr 28 17:27:20 2017
0 0
原创粉丝点击