This article is Senlie original, reprint please retain this address:Http://blog.csdn.net/zhengsenlie
1. File lock file system operation, more time-consuming
2. Thread locking is not only suitable for locking between threads in the same process, but also for locking between different processes.
3. Use thread lockout requirements between different processes:
1) The mutex variable must be stored in a memory area shared by all processes
2) must inform the thread function library This is a mutex that is shared between different processes
/* Include My_lock_init */#include "unpthread.h" #include <sys/mman.h>static pthread_mutex_t*mptr;/* actual mutex 'll is in shared memory */voidmy_lock_init (char *pathname) {intfd;pthread_mutexattr_tmattr;fd = Open ("/dev/zero", O_ Rdwr, 0);//1. Use the MMAP function to map/dev/zero to memory Mptr = mmap (0, sizeof (pthread_mutex_t), Prot_read | prot_write,map_shared, FD, 0);//close descriptor, because the descriptor has been mapped by the memory of Close (FD);//2. Call some Pthread library functions to tell the library: This is a mutex located in the shared memory area,// will be used for locking pthread_mutexattr_init between different processes (&MATTR); First, a pthread_mutexattr_t structure is initialized with a default property for a mutex pthread_mutexattr_setpshared (&mattr, pthread_process_shared); The structure is then given the pthread_process_shared attribute so that it can be used within multiple processes Pthread_mutex_init (mptr, &mattr); Finally call the Pthread_mutex_init function to initialize the mutex lock in the shared memory area with these properties}/* end My_lock_init *//* include my_lock_wait */voidmy_lock_wait () { Pthread_mutex_lock (mptr);} Voidmy_lock_release () {pthread_mutex_unlock (mptr);} /* End my_lock_wait */
UNIX Network Programming Volume 1 server Programming Paradigm 4 pre-derived subprocess to protect accept with thread Mutex lock mode