How can I call a thread several times in Python?

Sorry if this is a stupid question. I am trying to use several multithreading classes to complete different tasks, which involves reusing these multithreads at different times. But I'm not sure which method to use. The code is as follows:

class workers1(Thread): def __init__(self): Thread.__init__(self) def run(self): do some stuff class workers2(Thread): def __init__(self): Thread.__init__(self) def run(self): do some stuff class workers3(Thread): def __init__(self): Thread.__init__(self) def run(self): do some stuff WorkerList1=[workers1(i) for i in range(X)] WorkerList2=[workers2(i) for i in range(XX)] WorkerList2=[workers3(i) for i in range(XXX)] while True: for thread in WorkerList1: thread.run (start? join? or?) for thread in WorkerList2: thread.run (start? join? or?) for thread in WorkerList3: thread.run (start? join? or?) do sth . 

I am trying to get all threads in the entire WorkerList to start working at the same time, or at least start at about the same time. Once once they were all stopped, I would like to call all threads again.

If there was no loop, I can just use .start; but since I can only start the thread once, starting does not seem to fit here. If I use run, it seems that all threads start sequentially, not only threads in the same list, but also threads from different lists.

Can anybody help?

+4
source share
2 answers

there are many misconceptions here:

  • you can only start a specific thread instance once. but in your case, the for loop cycles through different instances of the thread, each instance is assigned to the thread variable in the loop, so there is no problem calling the start() method on each thread. (you can think of it as if the thread variable is an alias of the Thread() object created in your list)

  • run() does not match join() : the run() call is executed as if you were programming sequentially. The run() method does not start a new thread, it simply executes in instructions in the method, as for any other function call.

  • join() does not start anything: it only waits for the thread to complete. in order for join() work correctly for the stream, you must first call start() on that stream.

in addition, you should not be able to restart the stream after its completion: you need to recreate the stream object to restart it. One way to solve this problem is to call Thread.__init__() at the end of the run() method. however, I would not recommend doing this, as this will prohibit the use of the join() method to detect the end of a thread's execution.

+8
source

If you call thread.start() in loops, you will actually start each thread only once, because all the entries in your list are separate thread objects (it doesn't matter that they belong to the same class). You should never call the run() method of a thread directly - it must be called by the start() method. Calling it directly will not call it in a separate thread.

+1
source

All Articles