Wang Bucca
Wang Bucca

Reputation: 98

Why would a thread go to sleep?

I am learning python thread handling with the help of http://www.python-course.eu/threads.php The explanation of this piece of code really confuses me:

from thread import start_new_thread

num_threads = 0
def heron(a):
    global num_threads
    num_threads += 1

    # code has been left out, see above(some operations)
    num_threads -= 1
    return new

start_new_thread(heron,(99,))
start_new_thread(heron,(999,))
start_new_thread(heron,(1733,))
start_new_thread(heron,(17334,))

while num_threads > 0:
    pass

The code:

num_threads += 1

Reads the value of num_thread

A new int instance will be incremented or decremented by 1(I think an new int object will be created)

Assign the new value to num_threads

Errors like this happen in the case of increment assignments:

The first thread reads the variable num_threads, which still has the value 0. Here comes what is confusing: After having read this value, the thread is put to sleep by the operating system. Now it is the second thread's turn: It also reads the value of the variable num_threads, which is still 0, because the first thread has been put to sleep too early, i.e. before it had been able to increment its value by 1. Now the second thread is put to sleep. Now it is the third thread's turn, which again reads a 0, but the counter should have been 2 by now. Each of these threads assigns now the value 1 to the counter. Similiar problems occur with the decrement operation.

Upvotes: 2

Views: 92

Answers (1)

overactor
overactor

Reputation: 1789

The clue here is that threads are conceptually concurrent (they run besides each other) but are in practice sequential. Every core of your CPU can only do one operation at a time, so to give you the impression that your computer is multitasking, the CPU switches what it is doing at a very high rate. It is typically your operating system that takes care of this for you.

Since num_threads += 1 is actually two statements, namely temp_num = num_threads + 1 and num_threads = temp_num, it can happen that the thread your CPU is executing switches in between those two operations.

This illustrates some of the dangers of accessing shared data between several threads.

If you want to learn more about what you should and shouldn't do in threads, the keywords you should be looking for are thread safe.

It should be noted that if threads were truly concurrent, the situation wouldn't improve much, since you could still be reading from shared memory at the wrong time (or even while it's being written).

Upvotes: 2

Related Questions