Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding threading

Tags:

python

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")
like image 973
user4893295 Avatar asked Mar 18 '16 16:03

user4893295


People also ask

What is the process of threading?

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.

What is thread and how it works?

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.

How many types of threads are there?

Six Most Common Types of Threads NPT/NPTF. BSPP (BSP, parallel) BSPT (BSP, tapered) metric parallel.

How many threads should I use?

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.


1 Answers

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

like image 101
SpoonMeiser Avatar answered Oct 26 '22 08:10

SpoonMeiser