【问题标题】:semaphore concurrency信号量并发
【发布时间】:2013-03-21 20:48:10
【问题描述】:

在下面的代码中,不会在子级中创建一个互斥体,作为其父级的副本吗?因此,现在有两份互斥锁——一份在孩子身上,一份在父母身上。怎样才能同步?据我所知,您需要一份由多个进程共享的副本才能使其同步。

  #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);
  }

【问题讨论】:

标签: c linux concurrency synchronization semaphore


【解决方案1】:

您不得将mutexsemaphore 混淆。 semaphore 可能允许多个线程/进程访问资源,mutex 仅允许 ONE 并发访问资源。
here 所述,您需要创建一个named semaphore 以使跨进程同步成为可能。 您必须在父进程中创建一个semaphore,并在子进程中使用sem_open 来实现同步。

【讨论】:

  • 谢谢,我在学习同步时遇到了上面的代码sn-p,并且怀疑它是否可以工作。感谢您确认这一点,学习新事物的感觉很棒
  • 不要忘记,命名信号量会在程序的生命周期之后持续存在,除非它被显式取消链接(或在命令行中删除)。否则,当您下次运行程序时,这可能会导致真正的地狱,因为信号量仍然存在于程序上次退出时留下的任何值。
猜你喜欢
  • 2011-04-20
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 2020-10-28
  • 1970-01-01
  • 2018-12-01
  • 2023-03-13
  • 2018-03-26
相关资源
最近更新 更多