码迷,mamicode.com
首页 > 编程语言 > 详细

python 多线程

时间:2015-03-11 12:13:43      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

例一:不使用多线程

#-*-coding:utf-8-*-
#compare for multi threadsafety
import time

def worker():
    print "worker"
    time.sleep(1)
    return
if __name__=="__main__":
    for i in xrange(5):
        worker()

例二:使用多线程

#-*-coding:utf-8-*-
import threading
import time
 
def worker():
    print "worker"
    time.sleep(1)
    return
 
for i in xrange(5):
    t=threading.Thread(target=worker)
    t.start()

例三:返回线程和主线程

#-*-coding:utf-8-*-
import threading
import time
 
def worker():
    print "worker"
    time.sleep(1)
    return
 
for i in xrange(5):
    t=threading.Thread(target=worker)
    t.start()
print "current has %d threads" % (threading.activeCount() - 1)

例四:threading.enumerate()的使用。此方法返回当前运行中的Thread对象列表

#!/usr/bin/python
#test the variable threading.enumerate()
import threading
import time
 
def worker():
    print "test"
    time.sleep(2)
 
threads = []
for i in xrange(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()
 
for item in threading.enumerate():
    print item
 
print
 
for item in threads:
    print item


例五:threading.setDaemon()的使用。设置后台进程。

 

python 多线程

标签:

原文地址:http://www.cnblogs.com/bluewelkin/p/4329169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!