Let's talk about threading.
In multi-threading, to ensure the correctness of shared resources, we often use thread synchronization technology.
Turn some sensitive operations into atomic operations to ensure that only one thread in multiple threads at the same time performs this atomic operation.
What I use most is a mutex, also known as an exclusive lock. Second, there are read and write locks, semaphores, condition variables and so on.
In addition, we use signals to communicate between processes, send a signal to a process, set a signal processing function in the process, and then perform certain operations when the process receives a signal.
In fact, in the thread, we can also accept the signal, using this mechanism, we can also be used to implement thread synchronization. For more information see blog.csdn.net/aspnet_lyc/article/details/19904825
Besides, the process.
In the process, we can achieve synchronization between processes through some interprocess communication methods.
One of the things I've recently encountered is that many processes in a collection system process pool print logs to the same log file, which can be cumbersome if implemented through interprocess communication.
There is also a way, if the use of shared memory, different processes in the log messages through the shared memory into a thread-safe queue, and then establish a process responsible for the special print log, it can also ensure that the chaos,
Ensure the correctness of the log, but the amount of code is also many.
There is also a way to set up a mutex in shared memory for all processes to share.
If you can be like a thread, there is a simple mutex, when used as long as the lock, you can achieve the mutual exclusion between the process is good. Before the file lock, but also some impression, so I used it to achieve a process of mutual exclusion lock
#coding =utf-8 "" Process mutex lock. Actually it is implemented by file lock. "" " Import Fcntlclass 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)
Locking Processlock.lock ()
Release Processlock.unlock ()
Very simple to use, interested friends can give it a try.
Python implementation Process Lock