您的位置:首页 > 编程语言 > Python开发

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

2017-04-28 17:35 696 查看

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

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

#_*_coding:utf-8_*_
import threading
from time import sleep, ctime

"""
the process that have mode of thread
"""
_max_link = 30
# A pool of thread max-link
thread_pool = []
# A list for saving instantiations of thread
lock_pool = []
# A list for saving instantiation of Lock
count = 0
# A global var

def 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 :",count

if __name__ == '__main__':
main()


运行结果:

PROCESS START AT:  Fri Apr 28 17:27:08 2017
---$:True
PROCESS 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息