Trying to get my head around threading. In my code, it's only firing one thread, when I think it should go straight on to the second. I've been reading about locks and allocating but don't quite understand. What would I need to do here to let 2 threads run independently at the same time?
import thread
def myproc(item):
print("Thread fired for " + item)
while True:
pass
things = ['thingone', 'thingtwo']
for thing in things:
try:
thread.start_new_thread(myproc(thing))
except:
print("Error")
A process, in the simplest terms, is an executing program. One or more threads run in the context of the process. A thread is the basic unit to which the operating system allocates processor time. A thread can execute any part of the process code, including parts currently being executed by another thread.
Definition: A thread is a single sequential flow of control within a program. The real excitement surrounding threads is not about a single sequential thread. Rather, it's about the use of multiple threads running at the same time and performing different tasks in a single program.
Six Most Common Types of Threads NPT/NPTF. BSPP (BSP, parallel) BSPT (BSP, tapered) metric parallel.
Ideally, no I/O, synchronization, etc., and there's nothing else running, use 48 threads of task. Realistically, use about 95 threads may be better to exploit the max of your machine. Because: a core waits for data or I/O sometimes, so thread 2 could run while thread 1 not running.
You've got the signature to start_new_thread
wrong. You're calling myproc
and passing the result as an argument to start_new_thread
, which never happens as myproc
never terminates.
Instead, it should be:
thread.start_new_thread(myproc, (thing,) )
The first argument is the function (ie. the function object, not calling the function) and the second is a tuple of arguments.
See: https://docs.python.org/2/library/thread.html#thread.start_new_thread
Once you have your program actually starting both threads, you probably want to add a pause at the end because the threads will terminate when the main thread finishes.
Also, please consider using the threading
module instead of the thread
module, as it provides a much nicer higher level interface, such as a convenient way for waiting until your threads have finished executing.
See: https://docs.python.org/2/library/threading.html#module-threading
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