在python中创建c样式线程

时间:2012-09-20 21:27:48

标签: python

您好我是python的新手,想要在循环中创建多个线程(如C风格)

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

我不知道如何在python中做同样的事情?基本上我想要那个thread []变量作为全局将立即创建所有线程然后将一次启动。我已经编写了一个类似的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)

3 个答案:

答案 0 :(得分:1)

您认为这更好吗?

for i in range(5):
    command_string = "Thread-" + "%d" % i
    thread = Thread(i, command_string)
    thread.start()

答案 1 :(得分:0)

如果你想要一对一的等价物,那么可能就是这样:

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()

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