SoFunction
Updated on 2024-10-29

Python multi-threading threading module usage example analysis

This article example describes the Python multi-threading threading module usage. Shared for your reference, as follows:

Multi-threading - threading

Python's thread module is a low-level module, and python's threading module wraps threads in a way that makes them easier to use.

1. Using the threading module

single-threaded execution

#coding=utf-8
import time
def saySorry():
  print('Run a lap')
  (1)
if __name__ == "__main__":
  for i in range(5):
    saySorry()

Run results:

run
run
run
run
run

multithreaded execution

#coding=utf-8
import threading
import time
def saySorry():
  print('Run a lap')
  (1)
if __name__ == "__main__":
  for i in range(5):
    t = (target=saySorry)
    ()#Starting threads

Run results:

run
run
run
run
run

clarification

①. It is obvious by running it that it takes much less time to operate concurrently using multiple threads.
②. The created thread needs to call thestart() method to start the

2. The main thread will wait for all the child threads to finish before it ends

#coding=utf-8
import threading
from time import sleep,ctime,time
def run():
  for i in range(3):
    print('On the run... %d'%i)
    sleep(1)
def sing():
  for i in range(3):
    print('Singing... %d'%i)
    sleep(1)
if __name__ == "__main__":
  print('------start------' + ctime())
  t1 = (target=run)
  t2 = (target=sing)
  ()#Starting threads
  ()
  # sleep(5)# Mask this line of code and try it, does the program end immediately?
  print('------stop------' + ctime())

Run results:

------start------Thu Aug 24 13:38:28 2017
On the run... The zero.
------stop------Thu Aug 24 13:38:28 2017
Singing. I'm not sure what I'm doing.
On the run... One.
Singing. One.
On the run... Two.
Singing. Two.

3. View the number of threads

#coding=utf-8
import threading
from time import sleep,ctime,time
def run():
  for i in range(3):
    print('On the run... %d'%i)
    sleep(1)
def sing():
  for i in range(3):
    print('Singing... %d'%i)
    sleep(1)
if __name__ == "__main__":
  print('------start------' + ctime())
  t1 = (target=run)
  t2 = (target=sing)
  ()#Starting threads
  ()
  while True:
    length = len(())
    print('The current number of running threads is:' , length , ctime())
    if length <= 1:
      break
  # sleep(5)# Mask this line of code and try it, does the program end immediately?
  print('------stop------' + ctime())

Run results:

Not shown here due to large numbers 。。。。。。

4. Encapsulation of thread execution code - subclasses

#coding=utf-8
import threading
import time
class MyThread():
  def run(self):
    for i in range(3):
      (1)
      msg = 'i am '++'@'+str(i) #The name attribute holds the name of the current thread.
      print(msg)
if __name__ == "__main__":
  t = MyThread()
  ()

Run results:

i am Thread-1@0
i am Thread-1@1
i am Thread-1@2

Description:

pythonclass has a run method for defining the functional functions of the thread, which can be overridden in your own thread class. After creating an instance of your own thread, you can override this method in your own thread class by using the Thread class'start()method, you can start the thread, hand it over to the python VM for scheduling, and call the run method to execute the thread when the thread gets a chance to execute.

5. Order of execution of threads

#coding=utf-8
import threading
import time
class MyThread():
  def run(self):
    for i in range(3):
      (1)
      msg = 'i am '++'@'+str(i) #The name attribute holds the name of the current thread.
      print(msg)
def test():
  for i in range(5):
    t = MyThread()
    ()
if __name__ == "__main__":
  test()

Run results:

i am Thread-1@0
i am Thread-2@0
i am Thread-3@0
i am Thread-4@0
i am Thread-5@0
i am Thread-1@1
i am Thread-2@1
i am Thread-3@1
i am Thread-4@1
i am Thread-5@1
i am Thread-1@2
i am Thread-2@2
i am Thread-3@2
i am Thread-4@2
i am Thread-5@2

Description:

(The results of the run may not be the same, but they are generally consistent)

As we can see from the execution result of the code, the execution order of the multithreaded program is uncertain. When the execution of the sleep statement, the thread will be blocked (Blocked), to the end of the sleep, the thread into a ready (Runnable) state, waiting for scheduling. And the thread scheduler will choose a thread to execute by itself. The above code can only guarantee that each thread runs the entire run function, but the threads are started in order,

The order of execution of each loop in the run function cannot be determined.

summarize

1. Each thread must have a name, and although the above example does not specify the name of the thread object, python automatically assigns a name to the thread.
2. The thread completes when its run() method ends.
3. It is not possible to control the thread scheduler, but it is possible to influence the way threads are scheduled in other ways.
4. Several states of the thread

Multithreading - Shared Global Variables

#coding=utf-8
import threading
import time
g_num = 100
def work1():
  global g_num
  for i in range(3):
    g_num+=1
  print('work1 --- num = %d'%g_num)
def work2():
  global g_num
  print('work2 --- num = %d'%g_num)
if __name__ == "__main__":
  print('---start------g_num = %d'%g_num)
  t1 = (target=work1)
  ()
  # Delay for a while to make sure things get done in the t1 thread #
  (1)
  t2 = (target=work2)
  ()

Run results:

---start------g_num = 100
work1 --- num = 103
work2 --- num = 103

Readers interested in more Python related content can check out this site's topic: theSummary of Python process and thread manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorials》、《Python + MySQL Database Programming Tutorial for Beginnersand theSummary of common database manipulation techniques in Python

I hope that what I have said in this article will help you in Python programming.