How it works...

In this example, we created nine threads, each with their own name and duration property, according to the definition of the __init__ method.

We then run them using the start method, which is limited to executing the contents of the previously defined run method. Note that the process ID for each thread is the same, meaning that we are in a multithreaded process.

Also, note that the start method is not blocking: when it is executed, the control immediately goes to the next line, while the thread is started in the background. In fact, as you can see, the creation of threads does not take place in the order specified by the code. Likewise, thread termination is constrained to the value of the duration parameter, evaluated using the randint function, and passed by the parameter for each thread creation instance. To wait for a thread to finish, a join operation must be performed.

The output looks like this:

---> Thread#1 running, belonging to process ID 13084
---> Thread#5 running, belonging to process ID 13084
---> Thread#2 running, belonging to process ID 13084
---> Thread#6 running, belonging to process ID 13084
---> Thread#7 running, belonging to process ID 13084
---> Thread#3 running, belonging to process ID 13084
---> Thread#4 running, belonging to process ID 13084
---> Thread#8 running, belonging to process ID 13084
---> Thread#9 running, belonging to process ID 13084

---> Thread#6 over
---> Thread#9 over
---> Thread#5 over
---> Thread#2 over
---> Thread#7 over
---> Thread#4 over
---> Thread#3 over
---> Thread#8 over
---> Thread#1 over

End

--- 9.117518663406372 seconds ---
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.216.174