Reputation: 1011
Hi I am new to python and want to create multiple threads in a loop something like (in C style)
for (;i < 10; i++)
thread[i]= pthread_create(&thread[i],&attr,func)
I am not sure how to do the same in python? Basically I want have that thread[] variable as global will create all thread at once and then will start then in once. I have written a similar python program that does it but I think having it in above style will be better.
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)
Upvotes: 1
Views: 110
Reputation: 92647
If you want a 1-to-1 equivalent, then this might be it:
threads = []
for i in xrange(10):
t = Thread(target=aFunc, name="Thread-%d" % i)
t.start()
threads.append(t)
Or if you just want to build up the thread objects, and start them later at-will...
threads = []
for i in xrange(10):
t = Thread(target=aFunc, name="Thread-%d" % i)
threads.append(t)
threads[2].start()
Upvotes: 0
Reputation: 13518
Reuse your thread_create function and list comprehension to get what you want.
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()
Note:
threads = [thread_create(x) for x in range(5)]
is just shorthand for
threads = []
for x in range(5):
threads.append(thread_create(x))
Upvotes: 0
Reputation: 11322
You think this is better?
for i in range(5):
command_string = "Thread-" + "%d" % i
thread = Thread(i, command_string)
thread.start()
Upvotes: 1