Let's talk about threading
In multiple threads, in order 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 executes the atomic operation.
My most common is the mutex, also known as the exclusive lock. Then there are read and write locks, semaphores, condition variables and so on.
In addition, we use signals to communicate between processes, send signals to a process, set up signal processing functions in the process, and then perform certain actions when the process receives a signal.
In fact, in the thread, can also accept the signal, using this mechanism, we can also be used to implement thread synchronization. See Http://www.jb51.net/article/64977.htm for more information
Again, the process.
In the process, we can achieve synchronization between processes by means of interprocess communication.
I recently encountered a situation where a collection system process pool many processes in the same log file to print the log, if the implementation of interprocess communication, more trouble.
There is also a way, if the use of shared memory, different processes separate log messages through shared memory into a thread-safe queue, and then set up a process responsible for the printing of the log, so as to ensure that it will not be a big mess,
Ensure the correctness of the log, but the amount of code is also a lot.
There is also a way to set up a mutex in shared memory that all processes share.
If you can like a thread, there is a simple mutex, the use of the time as long as the lock, you can achieve mutual exclusion between processes. There was a lock on the file before, so I used it to implement a mutex 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 ()
Very simple to use, interested friends can have a try.