thread模塊的核心函數是thread.start_new_thread(),使用thread模塊的事例.
import thread
from time import ctime, sleep
loops = [4,2]
def loop(nloop, nsec, lock):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:' , ctime()
lock.release()
def main():
print 'starting at:', ctime()
locks = []
nloops = range(len(loops))
for i in nloops:
lock = thread.allocate_lock()
lock.acquire()
locks.append(lock)
for i in nloops:
thread.start_new_thread(loop,(i, loops[i], locks[i]))
for i in nloops:
while locks[i].locked():
pass
print 'all Done at: ', ctime()
if __name__ == '__main__':
main()
import threading
from time import sleep, ctime
class MyThread(threading.Thread):
"""docstring for MyThread"""
def __init__(self, func, args, name=''):
super(MyThread, self).__init__()
self.name = name
self.func = func
self.args = args
def getResult(self):
return self.res
def run(self):
self.res = self.func(*self.args)
loops = [4,2]
def loop(nloop, nsec):
print 'start loop', nloop, 'at: ', ctime()
sleep(nsec)
print 'loop done', nloop, 'at: ', ctime()
return 'ws'
def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops))
for i in nloops:
#t = threading.Thread(target = loop, args = (i, loops[i]))
t = MyThread(loop,(i,loops[i]),loop.__name__)
threads.append(t)
for i in nloops:
threads[i].start()
for i in nloops:
threads[i].join()
print threads[i].getResult()
if __name__ == '__main__':
main()
#!/usr/bin/env python
from atexit import register
from random import randrange
from threading import Thread, Lock, currentThread
from time import sleep, ctime
class CleanOutputSet(set):
def __str__(self):
return ', '.join(x for x in self)
lock = Lock()
loops = (randrange(2, 5) for x in xrange(randrange(3, 7)))
remaining = CleanOutputSet()
def loop(nsec):
myname = currentThread().name
lock.acquire()
remaining.add(myname)
print '[%s] Started %s' % (ctime(), myname) #print '[{0}] Started {1}'.format(ctime(), myname)
lock.release()
sleep(nsec)
lock.acquire()
remaining.remove(myname)
print '[%s] Completed %s (%d secs)' % ( #print '[{0}] Completed {1} ({2} secs)'.format(
ctime(), myname, nsec)
print ' (remaining: %s)' % (remaining or 'NONE') #print ' (remaining: {0})'.format(remaining or 'NONE')
lock.release()
def _main():
for pause in loops:
Thread(target=loop, args=(pause,)).start()
@register
def _atexit():
print 'all DONE at:', ctime()
if __name__ == '__main__':
_main()