简体   繁体   English

如何确定Linux中是否已存在互斥对象?

[英]How do you find out if a mutex object already exists in Linux?

I'm currently attempting to port a Multithreading library written for WIN32 to Android/Linux and I seem to have run into a bit of a problem trying to map over a particular feature that WIN32 mutexes have. 我目前正在尝试将为WIN32编写的多线程库移植到Android / Linux,并且试图映射到WIN32互斥体具有的特定功能时,似乎遇到了一些问题。

From the documentation for Windows Mutex Objects: 从Windows Mutex对象的文档中:

Threads in other processes can open a handle to an existing mutex object by specifying the object name in a call to CreateMutex. 通过在对CreateMutex的调用中指定对象名称,其他进程中的线程可以打开现有互斥对象的句柄。 If a mutex object with that name already exists, GetLastError returns ERROR_ALREADY_EXISTS. 如果已经存在具有该名称的互斥对象,则GetLastError返回ERROR_ALREADY_EXISTS。

I was not able to find any info on something in the Linux man pages that is similar to what the Windows API offers. 我无法在Linux手册页中找到与Windows API提供的信息类似的任何信息。

The main reason for my asking this question is that the mutex creation code I'm porting over contains: 我问这个问题的主要原因是我要移植的互斥量创建代码包含:

isCreator = !(::GetLastError() == ERROR_ALREADY_EXISTS);

where isCreator is a boolean data type. 其中isCreator是布尔数据类型。 (Not sure what it's used for , but I think its important). (不知道它的用途是什么,但我认为它很重要)。

edit: 编辑:

mutex = PTHREAD_MUTEX_INITIALIZER;
// attributes??

if (pthread_mutex_init(&mutex, NULL) != 0) {
 throw Nv_EXCEPTION(XCPT_ResourceAllocationFailure, GetLastError());
}

Your easiest analog to a named, interprocess mutex is probably a named realtime semaphore initialized to a value of one (1). 与命名的进程间互斥锁最简单的类比可能是已初始化为一(1)值的命名的实时信号量 Try to sem_open("/the_sem", O_CREAT|O_EXCL, mode, 1) . 尝试sem_open("/the_sem", O_CREAT|O_EXCL, mode, 1) O_EXCL will fail with EEXIST if you aren't the first, and a subsequent sem_open with no flags ought to succeed if you aren't the first: 如果您不是O_EXCL,则O_EXCL失败,并显示EEXIST;如果您不是第一个,则随后的没有标志的sem_open应该成功:

sem_t *sem;
int isCreator = 0;

if ((sem = sem_open("/the_sem", O_CREAT|O_EXCL, mode, 1)) != SEM_FAILED) {
  // We got here first
  isCreator = 1;
} else {
  if (errno != EEXIST) uh_oh_goodbye();

  // We're not first.  Try again
  sem = sem_open("/the_sem", 0);
  if (sem == SEM_FAILED) uh_oh_goodbye();
}

Note: you can share pthread mutexes (and anonymous realtime semaphores, for that matter) between processes, if the synchronization object is initialized in shared memory. 注意:您可以在进程间共享并行线程互斥(和匿名实时信号量,对于这个问题),如果同步对象在共享内存初始化。 POSIX shared memory realtime extensions permit shared memory to be named , too. POSIX共享内存实时扩展也允许命名共享内存 There's then a bit of a race between creating the shared memory and initializing the mutex, but in this case attempting to call pthread_mutex_init() should fail with EBUSY for all but the race winner. 然后,在创建共享内存和初始化互斥体之间会有一些竞争,但是在这种情况下,除了竞赛获胜者之外,所有人都无法通过pBUS_mutex_init pthread_mutex_init()调用EBUSY。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM