一、thread(不推荐)

1 import thread
2 def foo(a):
3     print a
4 
5 thread.start_new_thread(foo,(a))

二、threading

1 import threading
2 class MyThread(threading.Thread):
3 #    def __init__(self,a):
4 #        threading.Thread.__init__(self[,name=xxx])
5 #        self.a=a
6     def run(self):
7         pass
8 thr=MyThread()
9 thr.start()    

三、

1、Lock,RLock

1 #主线程 
2 mutex = threading.Lock()
3 #子线程 
4 mutex.acquire([timeout])
5 mutex.release()

2、Condition

#主线程
con = threading.Condition()
#子线程
con.acquire()
con.notify()
con.wait()
#...
con.release()

3、Queue

import Queue
#主线程
q=Queue.Queue() #FIFO,Maxsize
#子线程
q.put(msg)#(item,block=True,timeout=None)
q.get(msg)
#q.qsize()==0

4、threading.Event

5、thr.join([timeout]) 等待子线程执行结束

6、thr.setDaemon(bool)  设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False

7、getName(),setName(),isDaemon(),isAlive()

8、activeCount(),enumerate()

 四、

#coding=utf8
import threading
class MyTread(threading.Thread):
    def run(self):
        while True:
            mylock.acquire()
            if len(task)==0:
                mylock.release()
                break
            t=task[0];del task[0]
            mylock.release()
            pass

def main():
    global task,mylock
    task=range(100)
    mylock=threading.Lock()
    for i in range(5):
        t=MyThread()
#        lt.append(t)
        t.start()
    for t in [li for li in threading.enumerate() if li.name!='MainThread']: #lt
        t.join()
    print threading.activeCount(),[li.name for li in threading.enumerate()]

if __name__ == '__main__':
    main()

 

posted on 2013-11-27 16:38  perel  阅读(207)  评论(0编辑  收藏  举报