Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Multithreading

Python3 Multithreading

Multithreading is like executing several different programs at the same time; running multiple threads has the following advantages:

Each independent thread has an entry point for program execution, a sequential execution sequence and a program exit. But a thread cannot execute independently; it must exist within an application, which provides control over the execution of multiple threads.

Each thread has its own set of CPU registers, called the thread context, which reflects the state of the CPU registers from the last time that thread ran.

The instruction pointer and stack pointer registers are the two most important registers in a thread context; a thread always runs within the context of a process, and these addresses are used to mark memory in the address space of the process that owns the thread.

Threads can be divided into:

The two commonly used modules for threads in Python3 are:

The thread module has been deprecated. Users can use the threading module instead, so the "thread" module can no longer be used in Python3. For compatibility, Python3 renamed thread to "_thread".

Getting started with Python threads

There are two ways to use threads in Python: with a function, or by wrapping a thread object in a class.

Functional style: call the start_new_thread() function in the _thread module to create a new thread. The syntax is as follows:


_thread.start_new_thread ( function, args[, kwargs] )

Parameter description:

Example

#!/usr/bin/python3

import

_thread

import

time

Define a function for the thread

def

print_time

(

threadName

,

delay

)

:

   count

=

0

   

while

count

<

5

:

     

time

.

sleep

(

delay

)

      count +

=

1

     

print

(

"%s: %s"

%

(

threadName

,

time

.

ctime

(

time

.

time

(

)

)

)

)

Create two threads

try

:

   _thread.

start_new_thread

(

print_time

,

(

"Thread-1"

,

2

,

)

)

   _thread.

start_new_thread

(

print_time

,

(

"Thread-2"

,

4

,

)

)

except

:

   

print

(

"Error: unable to start thread"

)

while

1

:

   

pass

Running the above program produces the following output:


Thread-1: Wed Jan  5 17:38:08 2022
Thread-2: Wed Jan  5 17:38:10 2022
Thread-1: Wed Jan  5 17:38:10 2022
Thread-1: Wed Jan  5 17:38:12 2022
Thread-2: Wed Jan  5 17:38:14 2022
Thread-1: Wed Jan  5 17:38:14 2022
Thread-1: Wed Jan  5 17:38:16 2022
Thread-2: Wed Jan  5 17:38:18 2022
Thread-2: Wed Jan  5 17:38:22 2022
Thread-2: Wed Jan  5 17:38:26 2022

After running the above program you can press ctrl-c to exit.


Thread modules

Python3 provides support for threads through two standard libraries, _thread and threading.

_thread provides low-level, primitive threads and a simple lock; its functionality is rather limited compared with the threading module.

Besides containing all the methods of the _thread module, the threading module also provides the following methods:

- Create an instance of the `Thread` class. - `target`: the target function the thread will execute. - `args`: arguments of the target function, passed as a tuple. - `kwargs`: keyword arguments of the target function, passed as a dictionary. - `daemon`: specifies whether the thread is a daemon thread.

The threading.Thread class provides the following methods and attributes:

  1. __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None):

  2. InitializationThreadobject.
  3. group: The thread group, currently unused and reserved for future extension.
  4. target: The target function the thread will execute.
  5. name: The name of the thread.
  6. args: Arguments of the target function, passed as a tuple.
  7. kwargs: Keyword arguments of the target function, passed as a dictionary.
  8. daemon: Specifies whether the thread is a daemon thread.
  9. - Initialize a `Thread` object. - `group`: the thread group, currently unused and reserved for future extension. - `target`: the target function the thread will execute. - `name`: the name of the thread. - `args`: arguments of the target function, passed as a tuple. - `kwargs`: keyword arguments of the target function, passed as a dictionary. - `daemon`: specifies whether the thread is a daemon thread.
    1. start(self):

    2. Start the thread. It will call the thread'srun()method.
    3. - Start the thread. It will call the thread's `run()` method.
      1. run(self):

      2. The thread defines the code to execute in this method.
      3. - The thread defines the code to execute in this method.
        1. join(self, timeout=None):

        2. Wait for the thread to terminate. By default,join()blocks until the called thread terminates. If thetimeoutparameter is specified, it waits at mosttimeoutseconds.
        3. - Wait for the thread to terminate. By default, `join()` blocks until the called thread terminates. If the `timeout` parameter is specified, it waits at most `timeout` seconds.
          1. is_alive(self):

          2. Return whether the thread is running. If the thread has started and has not yet terminated, it returnsTrue; otherwise, returnsFalse。
          3. - Return whether the thread is running. If the thread has started and has not yet terminated, it returns `True`, otherwise `False`.
            1. getName(self):

            2. Return the name of the thread.
            3. - Return the name of the thread.
              1. setName(self, name):

              2. Set the name of the thread.
              3. - Set the name of the thread.
                1. identproperty through the following steps:

                2. The unique identifier of the thread.
                3. - The unique identifier of the thread.
                  1. daemonproperty through the following steps:

                  2. The daemon flag of the thread, indicating whether it is a daemon thread.
                  3. - The daemon flag of the thread, indicating whether it is a daemon thread.
                    1. isDaemon()method in the component:

                    A simple threading example:

                    Example

                    import

                    threading

                    import

                    time

                    def

                    print_numbers

                    (

                    )

                    :

                       

                    for

                    i

                    in

                    range

                    (

                    5

                    )

                    :

                           

                    time

                    .

                    sleep

                    (

                    1

                    )

                           

                    print

                    (

                    i

                    )

                    Create a thread

                    thread

                    =

                    threading

                    .

                    Thread

                    (

                    target

                    =

                    print_numbers

                    )

                    Start a thread

                    thread

                    .

                    start

                    (

                    )

                    Wait for the threads to finish

                    thread

                    .

                    join

                    (

                    )

                    The output is:

                    0
                    1
                    2
                    3
                    4
                    

                    Creating threads with the threading module

                    We can create a new subclass by inheriting directly from threading.Thread, instantiate it and call start() to launch a new thread, which calls the thread's run() method:

                    Example

                    #!/usr/bin/python3

                    import

                    threading

                    import

                    time

                    exitFlag

                    =

                    0

                    class

                    myThread

                    (

                    threading

                    .

                    Thread

                    )

                    :

                       

                    def

                    init

                    (

                    self

                    ,

                    threadID

                    ,

                    name

                    ,

                    delay

                    )

                    :

                           

                    threading

                    .

                    Thread

                    .

                    init

                    (

                    self

                    )

                           

                    self

                    .

                    threadID

                    =

                    threadID

                           

                    self

                    .

                    name

                    =

                    name

                           

                    self

                    .

                    delay

                    =

                    delay

                       

                    def

                    run

                    (

                    self

                    )

                    :

                           

                    print

                    (

                    "Starting thread: "

                    self

                    .

                    name

                    )

                            print_time

                    (

                    self

                    .

                    name

                    ,

                    self

                    .

                    delay

                    ,

                    5

                    )

                           

                    print

                    (

                    "Exiting thread: "

                    self

                    .

                    name

                    )

                    def

                    print_time

                    (

                    threadName

                    ,

                    delay

                    ,

                    counter

                    )

                    :

                       

                    while

                    counter:

                           

                    if

                    exitFlag:

                                threadName.

                    exit

                    (

                    )

                           

                    time

                    .

                    sleep

                    (

                    delay

                    )

                           

                    print

                    (

                    "%s: %s"

                    %

                    (

                    threadName

                    ,

                    time

                    .

                    ctime

                    (

                    time

                    .

                    time

                    (

                    )

                    )

                    )

                    )

                            counter -

                    =

                    1

                    Create new threads

                    thread1

                    =

                    myThread

                    (

                    1

                    ,

                    "Thread-1"

                    ,

                    1

                    )

                    thread2

                    =

                    myThread

                    (

                    2

                    ,

                    "Thread-2"

                    ,

                    2

                    )

                    Start the new threads

                    thread1.

                    start

                    (

                    )

                    thread2.

                    start

                    (

                    )

                    thread1.

                    join

                    (

                    )

                    thread2.

                    join

                    (

                    )

                    print

                    (

                    "Exiting main thread"

                    )

                    The result of running the above program is as follows;

                    
                    开始线程:Thread-1
                    开始线程:Thread-2
                    Thread-1: Wed Jan  5 17:34:54 2022
                    Thread-2: Wed Jan  5 17:34:55 2022
                    Thread-1: Wed Jan  5 17:34:55 2022
                    Thread-1: Wed Jan  5 17:34:56 2022
                    Thread-2: Wed Jan  5 17:34:57 2022
                    Thread-1: Wed Jan  5 17:34:57 2022
                    Thread-1: Wed Jan  5 17:34:58 2022
                    退出线程:Thread-1
                    Thread-2: Wed Jan  5 17:34:59 2022
                    Thread-2: Wed Jan  5 17:35:01 2022
                    Thread-2: Wed Jan  5 17:35:03 2022
                    退出线程:Thread-2
                    退出主线程
                    

                    Thread synchronization

                    If multiple threads modify the same data together, unpredictable results may occur; to ensure data correctness, the threads need to be synchronized.

                    Simple thread synchronization can be achieved with the Lock and RLock objects of Thread; both have acquire and release methods. For data that must be operated on by only one thread at a time, the operation can be placed between the acquire and release methods, as follows:

                    The advantage of multithreading is that several tasks can run at the same time (or at least it feels that way). But when threads need to share data, there can be data synchronization problems.

                    Consider this situation: all elements of a list are 0, the thread "set" changes all elements to 1 from back to front, while the thread "print" reads the list from front to back and prints it.

                    Then it may happen that just as the thread "set" starts changing, the thread "print" comes to print the list, so the output is half 0s and half 1s; this is data out of sync. To avoid this, the concept of a lock is introduced.

                    A lock has two states - locked and unlocked. Whenever a thread such as "set" wants to access shared data, it must first acquire the lock; if another thread such as "print" has already acquired the lock, then the thread "set" is paused, that is, synchronously blocked; once the thread "print" finishes accessing and releases the lock, the thread "set" can continue.

                    With this handling, printing the list outputs either all 0s or all 1s, and the awkward situation of half 0s and half 1s no longer occurs.

                    Example

                    #!/usr/bin/python3

                    import

                    threading

                    import

                    time

                    class

                    myThread

                    (

                    threading

                    .

                    Thread

                    )

                    :

                       

                    def

                    init

                    (

                    self

                    ,

                    threadID

                    ,

                    name

                    ,

                    delay

                    )

                    :

                           

                    threading

                    .

                    Thread

                    .

                    init

                    (

                    self

                    )

                           

                    self

                    .

                    threadID

                    =

                    threadID

                           

                    self

                    .

                    name

                    =

                    name

                           

                    self

                    .

                    delay

                    =

                    delay

                       

                    def

                    run

                    (

                    self

                    )

                    :

                           

                    print

                    (

                    "Starting thread: "

                    self

                    .

                    name

                    )

                           

                    Acquire the lock for thread synchronization

                            threadLock.

                    acquire

                    (

                    )

                            print_time

                    (

                    self

                    .

                    name

                    ,

                    self

                    .

                    delay

                    ,

                    3

                    )

                           

                    Release the lock to start the next thread

                            threadLock.

                    release

                    (

                    )

                    def

                    print_time

                    (

                    threadName

                    ,

                    delay

                    ,

                    counter

                    )

                    :

                       

                    while

                    counter:

                           

                    time

                    .

                    sleep

                    (

                    delay

                    )

                           

                    print

                    (

                    "%s: %s"

                    %

                    (

                    threadName

                    ,

                    time

                    .

                    ctime

                    (

                    time

                    .

                    time

                    (

                    )

                    )

                    )

                    )

                            counter -

                    =

                    1

                    threadLock

                    =

                    threading

                    .

                    Lock

                    (

                    )

                    threads

                    =

                    [

                    ]

                    Create new threads

                    thread1

                    =

                    myThread

                    (

                    1

                    ,

                    "Thread-1"

                    ,

                    1

                    )

                    thread2

                    =

                    myThread

                    (

                    2

                    ,

                    "Thread-2"

                    ,

                    2

                    )

                    Start the new threads

                    thread1.

                    start

                    (

                    )

                    thread2.

                    start

                    (

                    )

                    Add the thread to the thread list

                    threads.

                    append

                    (

                    thread1

                    )

                    threads.

                    append

                    (

                    thread2

                    )

                    Wait for all threads to complete

                    for

                    t

                    in

                    threads:

                        t.

                    join

                    (

                    )

                    print

                    (

                    "Exiting main thread"

                    )

                    Running the above program, the output is:

                    
                    开启线程: Thread-1
                    开启线程: Thread-2
                    Thread-1: Wed Jan  5 17:36:50 2022
                    Thread-1: Wed Jan  5 17:36:51 2022
                    Thread-1: Wed Jan  5 17:36:52 2022
                    Thread-2: Wed Jan  5 17:36:54 2022
                    Thread-2: Wed Jan  5 17:36:56 2022
                    Thread-2: Wed Jan  5 17:36:58 2022
                    退出主线程
                    

                    Thread priority queue (Queue)

                    Python's Queue module provides synchronized, thread-safe queue classes, including the FIFO (first in, first out) queue Queue, the LIFO (last in, first out) queue LifoQueue and the priority queue PriorityQueue.

                    These queues all implement lock primitives and can be used directly in multithreaded programs; queues can be used to achieve synchronization between threads.

                    Common methods in the Queue module:

                    Example

                    #!/usr/bin/python3

                    import

                    queue

                    import

                    threading

                    import

                    time

                    exitFlag

                    =

                    0

                    class

                    myThread

                    (

                    threading

                    .

                    Thread

                    )

                    :

                       

                    def

                    init

                    (

                    self

                    ,

                    threadID

                    ,

                    name

                    ,

                    q

                    )

                    :

                           

                    threading

                    .

                    Thread

                    .

                    init

                    (

                    self

                    )

                           

                    self

                    .

                    threadID

                    =

                    threadID

                           

                    self

                    .

                    name

                    =

                    name

                           

                    self

                    .

                    q

                    =

                    q

                       

                    def

                    run

                    (

                    self

                    )

                    :

                           

                    print

                    (

                    "Starting thread:"

                    self

                    .

                    name

                    )

                            process_data

                    (

                    self

                    .

                    name

                    ,

                    self

                    .

                    q

                    )

                           

                    print

                    (

                    "Exiting thread: "

                    self

                    .

                    name

                    )

                    def

                    process_data

                    (

                    threadName

                    ,

                    q

                    )

                    :

                       

                    while

                    not

                    exitFlag:

                            queueLock.

                    acquire

                    (

                    )

                           

                    if

                    not

                    workQueue.

                    empty

                    (

                    )

                    :

                                data

                    =

                    q.

                    get

                    (

                    )

                                queueLock.

                    release

                    (

                    )

                               

                    print

                    (

                    "%s processing %s"

                    %

                    (

                    threadName

                    ,

                    data

                    )

                    )

                           

                    else

                    :

                                queueLock.

                    release

                    (

                    )

                           

                    time

                    .

                    sleep

                    (

                    1

                    )

                    threadList

                    =

                    [

                    "Thread-1"

                    ,

                    "Thread-2"

                    ,

                    "Thread-3"

                    ]

                    nameList

                    =

                    [

                    "One"

                    ,

                    "Two"

                    ,

                    "Three"

                    ,

                    "Four"

                    ,

                    "Five"

                    ]

                    queueLock

                    =

                    threading

                    .

                    Lock

                    (

                    )

                    workQueue

                    =

                    queue.

                    Queue

                    (

                    10

                    )

                    threads

                    =

                    [

                    ]

                    threadID

                    =

                    1

                    Create new threads

                    for

                    tName

                    in

                    threadList:

                       

                    thread

                    =

                    myThread

                    (

                    threadID

                    ,

                    tName

                    ,

                    workQueue

                    )

                       

                    thread

                    .

                    start

                    (

                    )

                        threads.

                    append

                    (

                    thread

                    )

                        threadID +

                    =

                    1

                    Fill the queue

                    queueLock.

                    acquire

                    (

                    )

                    for

                    word

                    in

                    nameList:

                        workQueue.

                    put

                    (

                    word

                    )

                    queueLock.

                    release

                    (

                    )

                    Wait for the queue to empty

                    while

                    not

                    workQueue.

                    empty

                    (

                    )

                    :

                       

                    pass

                    Notify the threads that it is time to exit

                    exitFlag

                    =

                    1

                    Wait for all threads to complete

                    for

                    t

                    in

                    threads:

                        t.

                    join

                    (

                    )

                    print

                    (

                    "Exiting main thread"

                    )

                    The result of running the above program:

                    
                    开启线程:Thread-1
                    开启线程:Thread-2
                    开启线程:Thread-3
                    Thread-3 processing One
                    Thread-1 processing Two
                    Thread-2 processing Three
                    Thread-3 processing Four
                    Thread-1 processing Five
                    退出线程:Thread-3
                    退出线程:Thread-2
                    退出线程:Thread-1
                    退出主线程