實現同時運行多個線程工作,主要通過信號量的設置,但還是在一個CPU上執行,具體要實現的例子可以放在函數裏執行,實現單核多併發,還等待什麼...... #!/usr/bin/env python # -*- coding: utf-8 -*- import threading import time import random def work_func(): print "worker thread is started at %s"% threading.current_thread() random.seed() time.sleep(random.random()) print "worker thread is finished at %s"%threading.current_thread() def sinple_thread_demo(): for i in range(100): t=threading.Thread(target=work_func) t.start() def worker_func_lock(lock): lock.acquire() work_func() lock.release() gLock=threading.Lock() gSem=threading._Semaphore(100)#信號量,允許同時運行的線程數 def thread_demo_lock(): for i in range(100): #sl=threading.Thread(target=worker_func_lock,args=[gLock]) sl=threading.Thread(target=worker_func_lock,args=[gSem])#參數傳入信號量 sl.start() if __name__=="__main__": #sinple_thread_demo()#通過鎖實現串行 thread_demo_lock()
PYTHON 多線程信號量
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.