Aki*_*24x 7 c++ linux macos mutex interprocess
目前我正在使用C++将软件从Windows移植到Mac OS X.
在Windows中,全局名为mutex的状态为废弃状态,这意味着互斥锁的当前所有者进程在不释放互斥锁的情况下消失.(这可能是由应用程序崩溃引起的)
由于存在废弃状态,试图锁定被遗弃的互斥锁不会造成死锁.
如果没有废弃的状态,它将永远等待不属于任何人的互斥锁.
还有另一种方法是使用超时来假设如果无法在一定时间内获得互斥锁而放弃互斥锁,但与废弃的互斥方式相比,它并不是一个完美的解决方案.在最坏的情况下,意外地两个进程可以访问由互斥锁锁定的对象.
在Mac OS X/Linux中是否有任何互斥支持被放弃的状态?
我研究了boost库,boost库有一个名为mutex,但是那个基于共享文件,所以它没有放弃状态.
请给我一些建议.
小智 4
好吧,也许有点晚了,但您可以使用 将pthread_mutexattr_t互斥体属性设置为在pthread_mutexattr_setpshared(&mutexAttr, PTHREAD_PROCESS_SHARED);API 之间共享。该互斥锁值需要通过将其存储到命名共享内存中来在进程之间共享。
这是一个代码片段:
int key = ftok(NAMED_MEMORY, ID_TAG);
if (-1 == key)
{
printf("Unable to name shared memory\n");
exit(1);
}
// Create the segment exclusively (if the segment already exists then a combination of IPC_CREAT | IPC_EXCL returns an error EEXIST)
int m_iShmid = shmget(key, TOTAL_SIZE, READ_WRITE_PERMISSIONS | IPC_CREAT | IPC_EXCL);
if (m_iShmid < 0)
{
if (EEXIST == errno)
{
// if the shared memory already exists we only fetch the id to that memory
m_iShmid = shmget(key, TOTAL_SIZE, READ_WRITE_PERMISSIONS);
}
if (m_iShmid < 0)
{
printf("Unable to create shared memory - %s\n",strerror(errno));
exit(1);
}
else
printf("Attached to the existing shared memory\n");
}
else
printf("Created new shared memory\n");
// Now we attach the segment to our data space.
mutex = reinterpret_cast<pthread_mutex_t*>(shmat(m_iShmid, NULL, 0));
if (reinterpret_cast<pthread_mutex_t*>(-1) == mutex)
{
printf("Unable to attach shared memory to the process - %s\n",strerror(errno));
exit(1);
}
// Now we can set this mutex to be shared between processes
pthread_mutex_t* mutex;
pthread_mutexattr_t mutexAttr;
ret = pthread_mutexattr_init(&mutexAttr);
if(ret != 0)
{
printf("pthread_mutexattr_init failed - err=%d\n",ret);
exit(1);
}
ret = pthread_mutexattr_setpshared(&mutexAttr, PTHREAD_PROCESS_SHARED);
if(ret != 0)
{
printf("pthread_mutexattr_setpshared failed - err=%d\n",ret);
exit(1);
}
ret = pthread_mutexattr_setrobust_np(&mutexAttr, PTHREAD_MUTEX_ROBUST_NP);
if(ret != 0)
{
printf("pthread_mutexattr_setrobust_np failed - err=%d\n",ret);
exit(1);
}
ret = pthread_mutex_init(mutex, &mutexAttr);
if(ret != 0)
{
printf("pthread_mutex_init failed - err=%d\n",ret);
exit(1);
}
// ------ Use the mutex from here on between processes
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2455 次 |
| 最近记录: |