线程互斥好办,来个锁就可以了。那么进程怎么办?使用共享内存。代码如下:
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|使用共享内存作为进程互斥锁的代码】
推荐阅读
- Linux|109 个实用 shell 脚本
- linux笔记|linux 常用命令汇总(面向面试)
- Linux|Linux--网络基础
- linux|apt update和apt upgrade命令 - 有什么区别()
- linux|2022年云原生趋势
- Go|Docker后端部署详解(Go+Nginx)
- 开源生态|GPL、MIT、Apache...开发者如何选择开源协议(一文讲清根本区别)
- GitHub|7 款可替代 top 命令的工具