1

嗨,我是 python 新手,想在一个循环中创建多个线程,比如(C 风格)

for (;i < 10; i++)
 thread[i]= pthread_create(&thread[i],&attr,func)

我不确定如何在 python 中做同样的事情?基本上我想要那个 thread[] 变量,因为 global 将一次创建所有线程,然后一次启动。我已经编写了一个类似的 python 程序来完成它,但我认为采用上述风格会更好。

def thread_create(thread_number):
    command_string = "Thread-" + "%d" %thread_number
    thread = myThread(thread_number, command_string)
    thread.start()

# Start new Threads

for i in range(5):
    thread_create(i)
4

3 回答 3

1

你认为这更好吗?

for i in range(5):
    command_string = "Thread-" + "%d" % i
    thread = Thread(i, command_string)
    thread.start()
于 2012-09-20T21:36:43.927 回答
0

如果你想要一个 1 对 1 的等价物,那么这可能是它:

threads = []
for i in xrange(10):
    t = Thread(target=aFunc, name="Thread-%d" % i)
    t.start()
    threads.append(t)

或者,如果您只想构建线程对象,并在以后随意启动它们......

threads = []
for i in xrange(10):
    t = Thread(target=aFunc, name="Thread-%d" % i)
    threads.append(t)

threads[2].start()
于 2012-09-20T21:41:23.640 回答
0

重用你的 thread_create 函数和列表理解来得到你想要的。

def thread_create(thread_number):
    command_string = "Thread-" + "%d" %thread_number
    return myThread(thread_number, command_string)
    # start them later


# see note below
threads = [thread_create(x) for x in range(5)]

for t in threads:
    t.start()

笔记:

threads = [thread_create(x) for x in range(5)]

只是简写

threads = []
for x in range(5):
    threads.append(thread_create(x))
于 2012-09-20T21:44:25.597 回答