Home > Backend Development > Python Tutorial > Python multi-threaded programming 2

Python multi-threaded programming 2

高洛峰
Release: 2016-10-18 11:42:20
Original
1437 people have browsed it

As in the previous section, python's threading.Thread class has a run method, which is used to define the functional functions of the thread. This method can be overridden in your own thread class. After creating your own thread instance, you can start the thread through the start method of the Thread class and hand it over to the Python virtual machine for scheduling. When the thread gets a chance to execute, the run method will be called to execute the thread. Let's start with the first example:

# encoding: UTF-8
import threading
import time
  
class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm "+self.name+' @ '+str(i)
            print msg
def test():
    for i in range(5):
        t = MyThread()
        t.start()
if __name__ == '__main__':
    test()
Copy after login

Execution result:


I'm Thread-1 @ 0

I'm Thread-2 @ 0

I'm Thread-5 @ 0

I 'm Thread-3 @ 0

I'm Thread-4 @ 0

I'm Thread-3 @ 1

I'm Thread-4 @ 1

I'm Thread-5 @ 1

I 'm Thread-1 @ 1

I'm Thread-2 @ 1

I'm Thread-4 @ 2

I'm Thread-5 @ 2

I'm Thread-2 @ 2

I 'm Thread-1 @ 2

I'm Thread-3 @ 2


From the code and execution results, we can see that the execution order of multi-threaded programs is uncertain. When the sleep statement is executed, the thread will be blocked (Blocked). After the sleep ends, the thread enters the ready (Runnable) state, waiting for scheduling. Thread scheduling will select a thread for execution. The above code can only guarantee that each thread runs the entire run function, but the startup order of the threads and the execution order of each loop in the run function cannot be determined.

In addition, please note:

1. Each thread must have a name. Although the name of the thread object is not specified in the above example, python will automatically assign a name to the thread.

2. The thread is completed when its run() method ends.

3. The thread scheduler cannot be controlled, but the thread scheduling method can be affected in other ways.

The above example simply demonstrates creating a thread, actively suspending it, and exiting the thread. In the next section, we will discuss thread synchronization using mutex locks.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template