Thread

What is a thread?

A thread is a single sequential control flow within a program. It is a relatively independent, schedulable execution unit within a process, and is the basic unit for the system to independently schedule and dispatch the CPU, referring to the scheduling unit of a running program. Running multiple threads simultaneously in a single program to complete different tasks is called multithreading.

Creating a Thread

First we need to import the _thread thread module, which provides the functionality needed to start threads. Note that the module name is _thread (the underscore here is not a typo). We will also import the time module, so that we can use the sleep function to introduce some delays in our program.

import _thread
import time

Next, we will define the function to be executed in the thread. It simply loops 5 times, printing the current running time, with a certain delay in each loop. We will use the sleep method of the time module mentioned above to introduce a delay; the time module takes the number of seconds of delay as input. The parameter delay is the delay in seconds for a single iteration of the loop.

def print_time( threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print ("%s: %s sec" % ( threadName, time.localtime()[5] ))

    print("%s:End" %threadName)
    # End the thread
    _thread.exit()

To start our threads, we simply call the start_new_thread function of the _thread module, specifying the first parameter as the print_time function we defined earlier, and specifying it as a 2-tuple corresponding to the thread function parameters.

_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )

Finally, use a while condition to keep the program in an infinite loop, without executing any instructions:

while True:
    pass
The complete code is as follows; it starts two threads and prints output in loop iterations:
 1import _thread   # Import the thread module
 2import time      # Import the time module
 3
 4# Define the thread function, print the thread number and running time
 5def print_time( threadName, delay):  
 6    count = 0
 7    while count < 5:
 8        time.sleep(delay)
 9        count += 1
10        print ("%s: %s sec" % ( threadName, time.localtime()[5] ))
11
12    print("%s:End" %threadName)
13    # End the thread
14    _thread.exit()
15
16# Start thread 1
17_thread.start_new_thread( print_time, ("Thread-1", 2, ) )  
18# Start thread 2
19_thread.start_new_thread( print_time, ("Thread-2", 4, ) )  
20
21
22while True:  # Main loop
23    pass     # Empty statement
24

When the program runs, it produces the following results:

Thread-1: 4 sec
Thread-1: 6 sec
Thread-2: 6 sec
Thread-1: 8 sec
Thread-1: 10 sec
Thread-2: 10 sec
Thread-1: 12 sec
Thread-1:End
Thread-2: 14 sec
Thread-2: 18 sec
Thread-2: 22 sec
Thread-2:End

Note

  • Multithreading seems to run threads in parallel at the same time, but in fact, at any given moment, a CPU core can only perform the task of one process.

  • What is called multiprocessing/multitasking on today’s computers is actually achieved by speeding up the CPU’s execution. Because a CPU can perform hundreds of millions of calculations per second, it can switch between processes many times, so within a time that humans can perceive, it does look like they are being executed simultaneously.

Locking a Thread

In multithreading, all variables are shared by all threads, so any variable can be modified by any thread. Therefore, the greatest danger of sharing data between threads is that multiple threads modify the same variable at the same time, messing up the content. We will learn how to control access to shared resources. This control is necessary to prevent data corruption. In other words, to prevent simultaneous access to an object, we need to use a Lock object.

A thread lock has two states: locked and unlocked. It is created in the unlocked state. It has two basic methods, acquire() and release().

When the thread lock’s state is unlocked, acquire() changes the state to locked and returns immediately. When the state is locked, acquire() blocks until a call to release() in another thread changes it to unlocked, then the acquire() call resets it to locked and returns.

Attention

The release() method should only be called in the locked state; it changes the state to unlocked and returns immediately. If you try to release an unlocked lock, a RuntimeError is raised.

We change the above example to thread locking, as follows. Only one thread can successfully acquire the lock and then continue executing the code; the other threads continue to wait until they obtain the lock:
 1import _thread   # Import the thread module
 2import time      # Import the time module
 3
 4# Create a lock
 5lock=_thread.allocate_lock()
 6
 7# Define the thread function, print the thread number and running time
 8def print_time( threadName, delay):  
 9    count = 0
10    # Acquire the lock
11    if lock.acquire():
12        while count < 5:
13            time.sleep(delay)
14            count += 1
15            print ("%s: %s sec" % ( threadName, time.localtime()[5] ))
16        # Release the lock
17        lock.release()
18        print("%s:End" %threadName)
19        # End the thread
20        _thread.exit()
21
22# Start thread 1
23_thread.start_new_thread( print_time, ("Thread-1", 2, ) )  
24# Start thread 2
25_thread.start_new_thread( print_time, ("Thread-2", 4, ) )  
26
27
28while True:  # Main loop
29    pass     # Empty statement
30
31

Running results:

Thread-1: 2 sec
Thread-1: 4 sec
Thread-1: 6 sec
Thread-1: 8 sec
Thread-1: 10 sec
Thread-1:End
Thread-2: 14 sec
Thread-2: 18 sec
Thread-2: 22 sec
Thread-2: 26 sec
Thread-2: 30 sec
Thread-2:End

The benefit of a lock is that it ensures a certain piece of critical code can only be executed completely from beginning to end by one thread. The disadvantages are of course many: first, it prevents concurrent execution of multiple threads; a piece of code containing a lock can actually only be executed in single-thread mode, greatly reducing efficiency.