Linux/Shell|使用共享内存作为进程互斥锁的代码

线程互斥好办,来个锁就可以了。那么进程怎么办?使用共享内存。代码如下:

pthread_mutex_t* init_shm_mutex(const key_t mutex_key) { int shmid = shmget(mutex_key, sizeof(pthread_mutex_t), 0666 | IPC_CREAT); if (shmid == -1) { return NULL; }void* shm_addr = shmat(shmid, NULL, 0); if (shm_addr == (void *) -1) { return NULL; } pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED); pthread_mutexattr_setrobust( &mutex_attr, PTHREAD_MUTEX_ROBUST); pthread_mutex_t* shm_mutex = (pthread_mutex_t *)shm_addr; pthread_mutex_init(shm_mutex,&mutex_attr); return shm_mutex; }

使用时:
#define PROCESS_MUTEX_KEY 20181217 //process pthread_mutex_t* g_ProcessMutex = NULL void write_data_to_shared_memory(const uchar* data) { if (g_ProcessMutex == NULL) { g_ProcessMutex = init_shm_mutex(PROCESS_MUTEX_KEY); }pthread_mutex_lock(g_ProcessMutex); //do somethingpthread_mutex_unlock(g_ProcessMutex); }

进程方面的调用,这里就不讨论了。
【Linux/Shell|使用共享内存作为进程互斥锁的代码】

    推荐阅读