I am a building a console Sudoku Solver where the main objective is raw speed.
I now have a ManagerThread that starts WorkerThreads to compute the neibhbors of each cell. So one WorkerThread is started for each cell right now. How can I re-use an existing thread that has completed its work?
The Thread Pool Pattern seems to be the solution, but I don't understand what to do to prevent the thread from dying once its job has been completed.
ps : I do not expect to gain much performance for this particular task, just want to experiment how multi-threading works before applying it to the more complex parts of the code.
Thanks
Thread Pool: Reusing Existing Thread To Save MemoryThread Pool Pattern stands for reusing existing threads and running all new instructions without allocation of new threads. The thread pool controls the number of running threads and is widely used in production. This pattern has implementations in Java: Executors.
Calling the start() function on a terminated thread will result in a RuntimeError indicating that threads can only be started once. Instead, to restart a thread in Python, you must create a new instance of the thread with the same configuration and then call the start() function.
Once a thread enters dead state it cannot be restarted.
We can use use join() method of thread class. To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2. join, and T2 calls T1.
Have a look at the Java SE provided java.util.concurrent
API. You can create a threadpool using Executors#newFixedThreadPool()
and you can submit tasks using the ExecutorService
methods. No need to reinvent your own threadpool. Also see the Sun tutorial on the subject.
when using a thread pool (java.util.concurrent) , you never actually initialized a thread - but rather pass Runnables to the thread pool. you don't need to worry about the thread life-cycle, just do whatever work you need to do in the runnable and let it exit when it's done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With