使用多线程来执行成员函数

时间:2013-08-14 12:19:52

标签: python multithreading

我正在尝试使用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几次。但结果却没有。

我可以知道我错了吗?

2 个答案:

答案 0 :(得分:0)

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

for t in multi_threads:
    t.start()

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

答案 1 :(得分: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()

这确实为每个线程输出“Running” - 虽然在这种情况下每个线程在下一个线程开始之前运行完成,所以没有必要使用线程。