这是我到目前为止所做的:
from threading import Thread
import pdb
with open('data.txt') as f:
threadcount = sum(1 for _ in f)
print "There are " + str(threadcount) + " lines/threads."
pdb.set_trace()
def Main():
for line in threadcount:
line = Thread(target=timer, args=())
line.start()
print "Main Complete"
if __name__ == '__main__':
Main()
我想知道如何根据行数在函数中动态构建这些线程;所以它会迭代创建所需数量的线程?我不知道该做什么/下一步去哪里。
所以我想为我正在处理的文本文件中的每一行提供一个线程,通常不会超过10-20行。
编辑:
好的,这就是我现在拥有的: 来自线程导入线程
import pdb
with open('data.txt') as f:
threadcount = sum(1 for _ in f)
print "There are " + str(threadcount) + " lines/threads."
#pdb.set_trace()
def stuff():
print "stuff"
def Main():
for line in xrange(threadcount):
#line = Thread(target=stuff, args=())
line = Thread()
line.start()
print "this is thread " + str(line)
if __name__ == '__main__':
Main()
并产生此输出:
There are 10 lines/threads.
this is thread <Thread(Thread-1, started 11612)>
this is thread <Thread(Thread-2, started 20692)>
this is thread <Thread(Thread-3, started 22232)>
this is thread <Thread(Thread-4, stopped 21620)>
this is thread <Thread(Thread-5, stopped 5620)>
this is thread <Thread(Thread-6, started 20496)>
this is thread <Thread(Thread-7, started 13844)>
this is thread <Thread(Thread-8, started 17128)>
this is thread <Thread(Thread-9, started 20256)>
this is thread <Thread(Thread-10, started 11796)>
this is thread <Thread(Thread-11, started 12416)>
this is thread <Thread(Thread-12, started 7720)>
this is thread <Thread(Thread-13, started 18680)>
this is thread <Thread(Thread-14, started 21452)>
this is thread <Thread(Thread-15, stopped 5796)>
this is thread <Thread(Thread-16, started 8452)>
this is thread <Thread(Thread-17, started 20388)>
this is thread <Thread(Thread-18, started 16652)>
this is thread <Thread(Thread-19, stopped 872)>
this is thread <Thread(Thread-20, started 16480)>
那么为什么它最终会以20个线程而不是10个线程结束呢?为什么打印出来的数字长而不仅仅是一个数字呢?更改为xrange有什么关系?
答案 0 :(得分:1)
这一行错了:
for line in threadcount:
threadcount
是一个整数,你只能迭代序列。
如果您想多次迭代,可以使用xrange
:
>>> for time in xrange(3):
... print time
0
1
2
你需要:
for line in xrange(threadcount):
...