1

我正在尝试使用 python 编写多线程程序。由于我对python很陌生,如果我问了一些对你来说很常见的问题,我很抱歉。

这是我的主要代码:

multi_threads = []
simulator = Simulation(simulation_number)
    # Simulation is my class, run() is a member function

for i in range(0, thread_number):
    multi_threads.append(Thread(target = simulator.run, args = (start, end,)))

for i in range(0, thread_number):
    multi_threads[i].start()
    multi_threads[i].join()

并在Simulation::un

def run(self, start, end):
    # do something...
    print "in run"
    return

我希望能看到in run几次。但事实证明什么都没有。

我可以知道我错了吗?

4

2 回答 2

0

您需要调用.start()线程。所以在你的情况下:

for t in multi_threads:
    t.start()

编辑以更改运行开始(感谢评论者,我记错了方法名称)

于 2013-08-14T12:25:25.140 回答
0

这是一些完整的代码:

from threading import Thread

class Simulation(object):
    def __init__(self, n):
        pass

    def run(self, start, end):
        print "Running",start,end

simulation_number=None

start = None
end = None

thread_number=5


multi_threads = []
simulator = Simulation(simulation_number)
# Simulation is my class, run() is a member function


for i in range(0, thread_number):
    multi_threads.append(Thread(target = simulator.run, args = (i, end,)))

for i in range(0, thread_number):
    multi_threads[i].start()
    multi_threads[i].join()

这确实为每个线程输出“正在运行” - 尽管在这种情况下,每个线程在下一个线程启动之前运行到完成,所以使用线程没有意义。

于 2013-08-14T12:53:09.817 回答