[英]Trouble understanding named semaphore initialization
I need to share a ressource between threads using named semaphores.我需要使用命名信号量在线程之间共享资源。 I have a main thread, and X subthreads.我有一个主线程和 X 个子线程。
Do I have to use sem_open
with the O_CREAT
flag in my main thread, and then call sem_open
again in every subthreads, with the same name but without flags?我一定要使用sem_open
与O_CREAT
在我的主线程标记,然后调用sem_open
在每个子线程再次,具有相同的名称,但没有标志?
Or do I only have to call sem_open
once in my main thread and then use it's return value in all subthreads?还是我只需要在主线程中调用sem_open
一次,然后在所有子线程中使用它的返回值?
I tried both but I didn't get anything close to expected behaviour...我两个都试过了,但没有得到任何接近预期的行为......
You must use wait and signal functions in your threads after open your semaphore:打开信号量后,您必须在线程中使用等待和信号函数:
The sem_open(3) function creates a new named semaphore or opens an existing named semaphore. sem_open(3) 函数创建一个新的命名信号量或打开一个现有的命名信号量。 After the semaphore has been opened, it can be operated on using sem_post(3) and sem_wait(3).信号量打开后,可以使用 sem_post(3) 和 sem_wait(3) 对其进行操作。 When a process has finished using the semaphore, it can use sem_close(3) to close the semaphore.当进程使用完信号量后,它可以使用 sem_close(3) 关闭信号量。 When all processes have finished using the semaphore, it can be removed from the system using sem_unlink(3).当所有进程使用完信号量后,可以使用 sem_unlink(3) 将其从系统中删除。
Reference : sem_overview(7) — Linux manual page参考: sem_overview(7) — Linux 手册页
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.