Simple Application of Mutex Threading.Lock in python Multithreading
This article mainly explains the "simple application of mutex Threading.Lock in python multithreading". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the simple application of mutex Threading.Lock in python multithreading".
Threads share process resources
Each thread is independent of each other and does not have any relationship with each other, but the resources in the same process are shared by threads. If the resources are not allocated reasonably, the data will be destroyed and the results of thread running can not be expected. This phenomenon is called "thread unsafe".
Examples are as follows:
#-*-coding: utf-8-*-import threadingimport time def test_xc (): F = open ("test.txt", "a") f.write ("test_dxc" +'\ n') time.sleep (1) f.close () if _ name__ = ='_ main__': for i in xrange (5): t = threading.Thread (target=test_xc) t.start ()
The results show:
Second, mutex synchronization
Thread synchronization can ensure that multiple threads can safely access competitive resources, and the simplest synchronization mechanism is to introduce mutex locks. Mutexes introduce a state for resources: locked / non-locked. When a thread wants to change shared data, it is locked first, when the state of the resource is "locked" and cannot be changed by other threads; until the thread releases the resource and changes the state of the resource to "unlocked", other threads can lock the resource again. The mutex ensures that only one thread writes at a time, thus ensuring the correctness of data in the case of multiple threads.
The Lock class is defined in the threading module, which can easily handle locking:
# create lock mutex = threading.Lock () # lock mutex.acquire ([timeout]) # timeout is the timeout # release mutex.release ()
Where the locking method acquire can have an optional parameter timeout for timeout. If timeout is set, the lock can be determined by the return value after the timeout, so that some other processing can be done.
Third, use thread locks
#-*-coding: utf-8-*-import threadingimport time def test_xc (): F = open ("test.txt" "a") f.write ("test_dxc" +'\ n') time.sleep (1) mutex.acquire () # acquire lock f.close () mutex.release () # release lock if _ _ name__ ='_ main__': mutex = threading.Lock () # create lock for i in xrange (5): t = threading.Thread (target=test_xc) t.start ()
Running result
Thank you for reading, the above is the content of "simple application of mutex Threading.Lock in python multithreading". After the study of this article, I believe you have a deeper understanding of the simple application of mutex Threading.Lock in python multithreading, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!