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

来源:互联网 发布:linux改变用户所属组 编辑:程序博客网 时间:2024/06/05 09:31

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

Condition对象:条件变量对象能让线程停下来。等待其其他 线程满足了某个条件,如状态的改变或者值的改变


notify:让指定数量的线程满足条件
notifyAll:让所有数量的线程满足条件


#_*_coding:utf-8_*_import threadingfrom time import sleep, ctime_max_link = 5# A pool of thread max-link_thread_pool = []# A list for saving instantiations of threaddef loop(*args):    """A function for sleep sometime s ,and make global count ++"""    _index,_lock_con = args    print "start loop %s at: " % _index, ctime()    _lock_con.acquire()    _lock_con.wait()    print("run the thread: %s" % _index)    _lock_con.release()    sleep(2)    print "end loop %s at: " % _index, ctime()def thread_pool(*arg):    """A function that create instantiations of threading"""    _func, _LN ,_con_Lock= arg    for i in range(_LN):        t = threading.Thread(target=_func, args=(i,_con_Lock))        _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"""    _con_obj = threading.Condition()    print "process start at: ".upper(), ctime()    thread_pool(loop, _max_link,_con_obj)    thread_start(_max_link)    while True:        inp = raw_input("---$:")        if inp == "quit":            break        _con_obj.acquire()        _con_obj.notify(int(inp))        _con_obj.release()    print "process end at: ".upper(), ctime(),"now count :",countif __name__ == '__main__':    main()

运行结果

PROCESS START AT:  Fri Apr 28 18:06:40 2017start loop 0 at:  Fri Apr 28 18:06:40 2017start loop 1 at:  Fri Apr 28 18:06:40 2017start loop 2 at:  Fri Apr 28 18:06:40 2017start loop 3 at:  Fri Apr 28 18:06:40 2017start loop 4 at: ---$: Fri Apr 28 18:06:40 20171---$:run the thread: 0end loop 0 at:  Fri Apr 28 18:06:47 20172---$:run the thread: 1run the thread: 2end loop 1 at: end loop 2 at:   Fri Apr 28 18:06:52 2017Fri Apr 28 18:06:52 2017
0 0
原创粉丝点击