One, Python multithreading
Because the implementation of CPython uses the global Interpereter Lock (GIL), a single thread is executing in Python at the same time, simplifying the implementation of the Python interpreter, and the Python object model is natural ground path safe. If you want your application to use better resources on multi-core machines, it is recommended to use multiprocessing or concurrent.futures.processpoolexecutor. But if your program is IO-intensive, using threads is still a good choice.
Two ways to use Python multithreading
Instance:
Copy Code code as follows:
Import threading
Import time
def worker (num):
Print (Threading.currentthread (). GetName () + ' start ')
Time.sleep (10)
Print (Threading.currentthread (). GetName () + ' running ')
Print (Threading.currentthread (). GetName () + "" + str (num))
Print (Threading.currentthread (). GetName () + ' exit ')
Def deamon ():
Print (Threading.currentthread (). GetName () + ' start ')
Time.sleep (20)
Print (Threading.currentthread (). GetName () + ' running ')
Print (Threading.currentthread (). GetName () + ' exit ')
Print (Threading.currentthread (). GetName ())
D = Threading. Thread (name= ' Deamon ', Target=deamon)
D.setdaemon (True)
D.start ()
W = Threading. Thread (name= ' worker ', Target=worker, args= (10,))
W.start ()
Class Myworker (threading. Thread):
def __init__ (self, num):
Threading. Thread.__init__ (self)
Self.num = num
Self.thread_stop = False
def run (self):
Print (Self.getname () + ' start ')
Time.sleep (30)
Print (Self.getname () + ' running ')
Print (Self.getname () + "" + str (self.num))
Print (Self.getname () + ' exit ')
MW = Myworker (30)
Mw.setname ("Myworker")
Mw.start ()
Print (Threading.currentthread (). GetName ())
Print ("All Threads:")
Print ("------------")
For th in Threading.enumerate ():
Print (Th.getname ())
Print ("------------")
D.join ()
W.join ()
Mw.join ()
Print (Threading.currentthread (). GetName ())
The results of the operation are as follows:
1 two methods used by Python threads:
* * Call threading directly. Thread to construct the thread object, and the parameters for thread are as follows:
Class Threading. Thread (Group=none, Target=none, Name=none, args= (), kwargs={})
Group is none;
Target is the functional function that the thread will perform;
The name of the thread or the SetName () can be set after the object is constructed;
Args is a tuple type of parameter that can be used for multiple, if only one is also in the form of tuple, for example (1,);
Kwargs is the parameter of the Dict type, and also the naming parameter;
* * To achieve their own threading. A subclass of thread that requires overloading __init__ () and run ().
2) Threading. Other methods of the thread object:
Start (), which is used to start the thread;
Join (), wait until the thread is finished;
Setdeamon (), which sets the thread to be a deamon thread, must be called before the start () call, and the default is non-demon.
Note: Python's main thread exits when no Deamon thread exists.
3 static method of threading:
Threading.current_thread (), used to obtain the current thread;
Threading.enumerate (), used for multiple current-surviving threads;
Threading. The timer timer, which is actually a word type of thread, uses the following:
Copy Code code as follows:
def hello (): Print ("Hello, World")
t = Timer (30.0, hello)
T.start ()
4) logging is thread-safe
The logging module is thread-safe, so you can use logging to help debug multithreaded programs.
Copy Code code as follows:
Import logging
Logging.basicconfig (level=logging. DEBUG,
Format= "(% (threadname) -10s:% (message) s",
)
Logging.debug ("Wait_for_event_timeout starting")