[英]Inter-process Mutex in C using pthread_mutex
I am trying to understand how inter-process communication works with pthread_mutex I've read a bunch of info on the topic but I still cannot wrap my head around it.我试图了解进程间通信如何与 pthread_mutex 一起工作我已经阅读了很多关于该主题的信息,但我仍然无法理解它。
I understand that there seems to be an easier way using semaphores but I am not trying to use that but to learn how mmap and inter-process communication works in C.我知道使用信号量似乎有一种更简单的方法,但我并没有尝试使用它,而是要了解 mmap 和进程间通信在 C 中是如何工作的。
Let's say I have the following code in "Process 1"假设我在“进程 1”中有以下代码
...
if (!initialized) {
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
pthread_mutex_init(&mtx->mtx, &attr);
// save to shared memory
} else {
// get the mutex from shared memory
}
...
Then I start the a copy of the same process and want to check if the mutex is already initialized and in shared memory.然后我启动同一进程的副本并想检查互斥锁是否已初始化并在共享 memory 中。 How to:
如何:
Ended up using Shawn's solution and just used a lock on a file it is a whole lot easier to setup and works similarly on Windows so I can easily write cross-platform wrapper code if needed.最终使用了 Shawn 的解决方案,并且只在文件上使用了锁,它更容易设置并且在 Windows 上的工作方式类似,因此我可以在需要时轻松编写跨平台包装器代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.