多線程筆記

import threading
import queue
import time
import random
 
'' '
1 .建立一個 Queue.Queue() 的實例,而後使用數據對它進行填充。
2 .將通過填充數據的實例傳遞給線程類,後者是經過繼承 threading.Thread 的方式建立的。
3 .每次從隊列中取出一個項目,並使用該線程中的數據和 run 方法以執行相應的工做。
4 .在完成這項工做以後,使用 queue.task_done() 函數向任務已經完成的隊列發送一個信號。
5 .對隊列執行 join 操做,實際上意味着等到隊列爲空,再退出主程序。
'' '
 
class jdThread(threading.Thread):
     def __init__(self,index,queue):
         threading.Thread.__init__(self)
         self.index = index
         self.queue = queue
 
     def run(self):
         while True:
             time.sleep( 1 )
             item = self.queue.get()
             if item is None:
                 break
             print( "序號:" ,self.index, "任務" ,item, "完成" )
             self.queue.task_done()#task_done方法使得未完成的任務數量- 1
 
q = queue.Queue( 0 )
'' '
初始化函數接受一個數字來做爲該隊列的容量,若是傳遞的是
一個小於等於 0 的數,那麼默認會認爲該隊列的容量是無限的.
'' '
for i in range( 2 ):
     jdThread(i,q).start()#兩個線程同時完成任務
 
for i in range( 10 ):
     q.put(i)#put方法使得未完成的任務數量+ 1


http://www.2cto.com/kf/201504/395335.html


同步:html

  1. from multiprocessing import Process, Lock  python

  2.   

  3. def l(lock, num):  dom

  4.     lock.acquire()  函數

  5.     print "Hello Num: %s" % (num)  ui

  6.     lock.release()  spa

  7.   

  8. if __name__ == '__main__':  線程

  9.     lock = Lock()  code

  10.   

  11.     for num in range(20):  htm

  12.         Process(target=l, args=(lock, num)).start() 繼承

http://www.runoob.com/python/python-multithreading.html

相關文章
相關標籤/搜索