37,744
社区成员




1#!/usr/bin/env python
2
3 import threading
4 import pdb
5 from time import sleep, ctime
6
7 class MyThread(threading.Thread):
8 def __init__(self, func, args, name=''):
9 threading.Thread.__init__(self)
10 self.name = name
11 self.func = func
12 self.args = args
13
14 def run(self):
15 #pdb.set_trace()
16 apply(self.func, self.args)
17
18 class TestThread(object):
19 def __init__(self):
20 self.loops = [ 4, 2 ]
21 pass
22
23 def loop(nloop, nsec):
24 print 'start loop', nloop, 'at:', ctime()
25 sleep(nsec)
26 print 'loop', nloop, 'done at:', ctime()
27
28 def main(self):
29 print 'starting at:', ctime()
30 threads = []
31 nloops = range(len(self.loops))
32
33 for i in nloops:
34 t = MyThread(self.loop, (i, self.loops[i]), self.loop.__name__)
35 threads.append(t)
36
37 for i in nloops:
38 threads[i].start()
39
40 for i in nloops:
41 threads[i].join()
42
43 print 'all DONE at:', ctime()
44
45 if __name__ == '__main__':
46 test = TestThread()
47 test.main()