The Python thread lock requires us to constantly learn related technologies. In fact, sometimes we can also find solutions to problems during continuous learning. Multithreading is an important aspect in programming, especially in the Deamon program of the server. Regardless of the system, the thread scheduling overhead is much faster than the traditional process.
Python supports multiple threads. Allows you to quickly create threads, mutex locks, semaphores, and other elements, and supports synchronization and mutex between read and write threads. In the US, Python runs on a Python virtual machine. The multi-thread created may be a virtual thread and needs to be polling and scheduled by the Python virtual machine, which greatly reduces the availability of Python multi-thread. We hope that later versions of Python can solve this problem and maximize the efficiency of multiple CPUs.
Some friends on the Internet say there are two ways to achieve the benefits of real multi-CPU:
1. You can create multiple processes instead of threads. The number of processes is the same as that of the cpu.
2. Using Jython or IronPython, you can get real multithreading.
Create a Python thread lock
Use the Thread class of the threading module. The class interface is as follows:
- class Thread( group=None, target=None, name=None,
args=(), kwargs={})
Target and args. target are target functions that require Sub-threads to run, and args are function parameters that are passed in the form of tuple.
The following code creates a subthread pointing to the worker Function
- def worker(a_tid,a_account):
- ...
- th = threading.Thread(target=worker,args=(i,acc) ) ;
Start the Python thread lock
- th.start()
Wait until the Thread returns threading. Thread. join (th) or th. join ()
If you can divide the data to be processed and there is no need to communicate between threads, You can compile your multi-threaded program in the following way: Create = run = recycle. However, if the threads need to access a common object, the mutex lock or semaphore must be introduced to access resources mutex.
The following describes how to create a mutex lock and create a lock.
- g_mutex = threading.Lock()
- ....
Use Python thread lock
- For ...:
- # Lock, mutual access exclusive from the next code to before release
- G_mutex.acquire ()
- A_account.deposite (1)
- # Release
- G_mutex.release ()
The above is an introduction to the Python thread lock system. I hope you will gain some benefits.