Python multi-thread operation instance and python multi-thread instance
I. python Multithreading
Because the implementation of CPython uses Global Interpereter Lock (GIL), only one thread is executing in python at the same time, which simplifies the implementation of the python interpreter, the python object model is naturally thread-safe. If you want your applications to use better resources on multi-core machines, we recommend that you use multiprocessing or concurrent. ures. processpoolexecutor. However, if your program is IO-intensive, it is still a good choice to use the thread.
2. Two methods for using python Multithreading
Instance:
Copy codeThe Code is 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 () + 'eg ')
Def deamon ():
Print (threading. currentThread (). getName () + 'start ')
Time. sleep (20)
Print (threading. currentThread (). getName () + 'running ')
Print (threading. currentThread (). getName () + 'eg ')
Print (threading. currentThread (). getName ())
D = threading. Thread (name = 'demoon', 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 running result is as follows:
1) Two methods used by the python thread:
** Directly call threading. Thread to construct the thread object. The Thread parameters are as follows:
Class threading. Thread (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. You can also call setName () to set it after the object is constructed;
Args is a tuple type parameter, which can be multiple. If only one parameter can be input in the tuple format, for example (1 ,);
Kwargs is a dict-type parameter, that is, a named parameter;
** To implement your own threading. Thread subclass, You Need To overload _ init _ () and run ().
2) Other methods of threading. Thread object:
Start (), used to start the thread;
Join (), wait until the thread ends;
SetDeamon (): Set the thread to deamon. It must be called before start (). The default value is demon.
Note: The main python thread exits when no non-deamon thread exists.
3) Static threading method:
Threading. current_thread (), used to obtain the current thread;
Threading. enumerate (), used by all the threads currently alive;
Threading. Timer is actually a word type of thread. It is used as follows:
Copy codeThe Code is 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 multi-threaded programs.
Copy codeThe Code is as follows:
Import logging
Logging. basicConfig (level = logging. DEBUG,
Format = "(% (threadName)-10 s: % (message) s ",
)
Logging. debug ("wait_for_event_timeout starting ")