c - 信号量并发

标签 c linux concurrency synchronization semaphore

在下面的代码中,是否会在子项中创建互斥量作为其父项的副本?因此,现在有两份互斥量——一份在 child 中,一份在 parent 中。怎么才能同步呢?据我所知,您需要一个由多个进程共享的副本才能使其同步。

  #include <semaphore.h>
  #include <stdio.h>
  #include <errno.h>
  #include <stdlib.h>
  #include <unistd.h>
  #include <sys/types.h>
  #include <sys/stat.h>
  #include <fcntl.h>
  #include <sys/mman.h>

  int main(int argc, char **argv)
  {
    int fd, i,count=0,nloop=10,zero=0,*ptr;
    sem_t mutex;

    //open a file and map it into memory

    fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU);
    write(fd,&zero,sizeof(int));

    ptr = mmap(NULL,sizeof(int), PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

    close(fd);

    /* create, initialize semaphore */
    if( sem_init(&mutex,1,1) < 0)
      {
        perror("semaphore initilization");
        exit(0);
      }
    if (fork() == 0) { /* child process*/
      for (i = 0; i < nloop; i++) {
        sem_wait(&mutex);
        printf("child: %d\n", (*ptr)++);
        sem_post(&mutex);
      }
      exit(0);
    }
    /* back to parent process */
    for (i = 0; i < nloop; i++) {
      sem_wait(&mutex);
      printf("parent: %d\n", (*ptr)++);
      sem_post(&mutex);
    }
    exit(0);
  }

最佳答案

您不能将 mutexsemaphore 混淆。 信号量 可能允许多个线程/进程访问资源,互斥锁 只允许ONE 并发访问资源。
如前所述here您将需要创建一个命名信号量 以使跨进程同步成为可能。 您必须在您的父进程中创建一个信号量,并且访问是在子进程中使用sem_open 来实现同步。

关于c - 信号量并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15557773/

相关文章:

java - 如何知道是否有任何预定的定时器

c# - 如何合并多个异步调用的结果

python - multiprocessing.Semaphore 和 multiprocessing.BoundedSemaphore 有什么区别?

c - 使用ffmpeg c连接视频和音频时如何计算pts和dts

c - GetProcAddress 为所有函数返回 0

c - 如何调整 VirtualAlloc 分配的区域?

linux - 使用 sox 转换为 .dat 格式的值似乎没有被规范化

c++ - 对 `main' 的 undefined reference ,当 main 存在时

c++ - 可移植的方式(linux 和 Windows)使文件只能由 1 个进程修改,而不能由 C/C++ 中的其他进程修改

c - 为什么clang用-O0产生效率低的asm(对于这个简单的 float 和)?