Python simple process lock code instance, python instance
Let's talk about threads first
In multithreading, thread synchronization is often used to ensure the correctness of shared resources.
Convert some sensitive operations into atomic operations to ensure that only one thread is executing the atomic operation in multiple threads at the same time.
I usually use mutex locks, also known as exclusive locks. There are also read/write locks, semaphores, and conditional variables.
In addition, we use signals to send signals to a process during inter-process communication. In this process, we set the signal processing function, and then execute some operations when the process receives signals.
In fact, the thread can also accept signals. Using this mechanism, we can also implement thread synchronization. For more information, see http://www.bkjia.com/article/64977.htm
Process
In the process, we can implement inter-process synchronization through some inter-process communication methods.
Recently, many processes in a collection system process pool print logs to the same log file.
Another way is to share the memory. Different processes put log messages in a thread-safe queue through the shared memory, and then create a process to print logs, in this way, we can avoid chaos,
Ensure the log correctness, but the amount of code is also large.
Another way is to set a mutex lock in the shared memory for all processes to share.
If there is a simple mutex lock like a thread, as long as the lock is used, it will be able to achieve mutual exclusion between processes. Previously, I was somewhat impressed with the file lock, so I used it to implement a mutex lock between processes.
#coding=utf-8 """ Process mutex lock. Actually it is implemented by file lock. """ import fcntl class ProcessLock(object): __lockfd = None @staticmethod def lock(): ProcessLock.__lockfd = open(__file__, 'a+') fcntl.flock(ProcessLock.__lockfd, fcntl.LOCK_EX) @staticmethod def unlock(): fcntl.flock(ProcessLock.__lockfd, fcntl.LOCK_UN)
Lock ProcessLock. lock ()
Release ProcessLock. unlock ()
It is very easy to use. If you are interested, you can try it.