Python中利用可调用对象创建线程的问题?
创建了一个实现了__call__()方法的类,然后利用该类实例创建线程。经过调试发现,线程刚刚start()就显示stopped了。不知道问题在哪里。参考Python核心编程写的。代码如下:
#!/usr/bin/env python
import threading
from time import ctime, sleep
nloops = [4,2]
class ThreadFunc(object):
def __init__(self, func, args, name=' '):
self.func = func
self.args = args
self.name = name
def __call__(self): # make instances of the class callable
map(self.func, self.args)
print('hello', self.func, 'args: ', self.args)
def loops(nloop, nsec):
print('Start thread ', nloop, 'at ', ctime())
sleep(nsec)
print('End thread ', nloop, 'at ', ctime())
def main():
print('All start at: ', ctime())
threads = []
nloop = range(len(nloops))
# create thread objects
for i in nloop:
# alternatives to create thread objects
t = threading.Thread(target=ThreadFunc(loops, (i, nloops[i]), loops.__name__))
threads.append(t)
# start all threads
for i in nloop:
threads[i].start()
# wait for all threads
for i in nloop:
threads[i].join()
print('All end at: ', ctime())
if __name__ == '__main__':
main()
[解决办法]
把map(self.func, self.args)改成
self.func(self.args[0],self.args[1])