What are some real world uses of the named semaphores?

时间:2018-05-28 18:54:19

标签: c multithreading unix concurrency semaphore

In UNIX-like systems we have both unnamed semaphores and named semaphores. For basically everything I've done, since I'd have to pass the pointer to the actual data to access, I always managed to pass the semaphore too, to whatever thread had to access the resource itself. Simple technique: creating a struct with both the object and the semaphore.

What are some cases in which it's best to use a named semaphore?

1 个答案:

答案 0 :(得分:1)

正如jspcl所说的那样。命名信号量用于进程之间的同步。在两个进程之间不能共享相同的地址(因为在某些嵌入式操作系统中存在一些例外,例如完整性,qnx等。)。因为每个进程都有不同的地址空间,其中地址页不同。

所以命名的信号量用于访问进程之间的共享内存。

例如,              Linux中的shmget()posix调用用于命名信号量。在此调用中,您必须具有char *的信号量名称以及该进程的内存的读写权限。它将返回与共享内存关联的信号量的文件描述符。之后,你必须调用mmap来获取共享内存地址。你可以通过它读写共享内存。

现实世界的例子是使用多个处理器的航空。一个过程将与其他电子部件交互,并将信息发送到其他处理器。因此在其他处理器中必须有可以从串口读取数据然后发送到其他进程的进程。所以这里使用名为信号量的多进程通信