SoFunction
Updated on 2024-11-12

Example of python multithreaded operation

I. python multithreading

This is because CPython's implementation uses the Global Interpereter Lock (GIL), which makes it possible to have only one thread executing in python at the same moment, thus simplifying the implementation of the python interpreter, and the python object model is naturally thread-safe. If you want your application to use better resources on a multi-core machine, it is recommended to use multiprocessing or . But if your program is IO-intensive, then using threads is still a good choice.

Second, python multi-threaded use of the two methods

Example:

Copy Code The code is as follows.

import threading
import time

def worker(num):
  print (().getName() + ' start')
  (10)
  print (().getName() + ' running')
  print (().getName() + " " + str(num))
  print (().getName() + ' exit')
 
def deamon():
  print (().getName() + ' start')
  (20)
  print (().getName() + ' running')
  print (().getName() + ' exit')
 
print(().getName())

d = (name='deamon', target=deamon)
(True)
()

w = (name='worker', target=worker, args=(10,))
()

class myWorker():
    def __init__(self, num): 
        .__init__(self) 
        = num 
        self.thread_stop = False 
  
    def run(self):
        print (()+' start')
        (30)
        print (()+' running')
        print (()+" " + str())
        print (()+' exit')
 
mw = myWorker(30)
("MyWorker")
()

print(().getName())

print("All threads:")
print("------------")
for th in ():
  print(())
print("------------")

()
()
()

print(().getName())

The results of the run are as follows:

1) Two ways to use python threads:

** Directly called to construct the thread object, Thread is parameterized as follows:
class (group=None, target=None, name=None, args=(), kwargs={}) 
group is None;
target is the function to be executed by the thread;
name is the name of the thread, which can also be set by calling setName() after the object is constructed;
args is a tuple type parameter, can be more than one, if there is only one also use the tuple form to pass, such as (1,);
kwargs is a dict type parameter, i.e., a bit-named parameter;

** Implementing your own subclasses requires overloading __init__() and run().

2) Other methods of the object:

start(), used to start the thread;
join(), wait until the thread ends;
setDeamon(), sets the thread to be a deamon thread, must be called before start() is called, defaults to non-deamon.
Note: python's main thread exits when no non-deamon thread exists.

3) Static methods of threading.

threading.current_thread() , used to get the current thread;
(), which is used to multi-thread all currently living threads;
Timer, which is actually a word type of thread, is used as follows:

Copy Code The code is as follows.

def hello(): print("hello, world")  
t = Timer(30.0, hello)
()

4) Logging is thread-safe!

The logging module is thread-safe, so you can use logging to help debug multithreaded programs.

Copy Code The code is as follows.

import logging
(level=,
format="(%(threadName)-10s : %(message)s",
)
("wait_for_event_timeout starting")