c - 使用信号量同步来自不同进程的线程

标签 c linux multithreading semaphore

我在 C 中遇到信号量问题。我有一个父进程和一个子进程。两者都可以创建 3 个线程,我必须显示线程的开始和结束,并且我必须强加下一个条件:来自父进程的 id 为 1 的线程必须在子进程的 id 为 2 的线程显示其结束之后显示其开始。我使用信号量,但是当我等待时,来自父进程的 id 为 1 的线程不会停留在信号量并继续显示开头。我无法使用函数 usleep() 或 sleep()。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <semaphore.h>


sem_t* s=NULL;

void* function1(void* arg)
{
   int* nrth=(int*) arg;
   sem_t   * s=NULL;

   s=sem_open("mysemaphore",O_EXCL);
   if(s==NULL)
       perror("Error");

   if(*nrth==1)
       sem_wait(s);


   printf("Begin P1, thread %d\n",*nrth);
   printf("End P1, thread %d\n",*nrth);


   sem_close(s);
   return 0;

}



void* function2(void* arg)
{
    int* nrth=(int*) arg;

    sem_t   * s=NULL;
    s=sem_open("mysemaphore",O_EXCL);
    if(s==NULL)
        perror("Error");

    printf("Begin P2, thread %d\n",*nrth);
    printf("End P2, thread %d\n",*nrth);

    if(*nrth==2)
       sem_post(s);

    sem_close(s);

    return 0;
}


int main()
{
   sem_unlink("mysemaphore");
   s=sem_open("mysemaphore",O_CREAT,0644,1);
   if(s==NULL)
      perror("ERROR!");


   pthread_t threads[4];
   int index[4];
   pthread_t threads2[4];
   int index2[4];

   if(fork()==0)
   {

      printf("Begin: process 2 \n");

       for(int i=1; i<=3; i++)
       {
          index2[i]=i;
          pthread_create(&threads2[i],NULL,function2,&index2[i]);
       }
       for(int i=1; i<=3; i++)
       {
          pthread_join(threads2[i],NULL);
       }
       printf("End: process 2 \n");
   }
   else
   {
       printf("Begin: process 1\n");

       for(int i=1; i<=3; i++)
       {
          index[i]=i;
          pthread_create(&threads[i],NULL,function1,&index[i]);
       }

       for(int i=1; i<=3; i++)
       {
           pthread_join(threads[i],NULL);
       }
       printf("End: process 2 \n");

       wait(NULL);
   }
   return 0;
}

最佳答案

当您调用 sem_destroy() 时,您正在破坏 function1()function2() 中的信号量,之后的行为该信号量未定义。这可能是你最大的问题。

在使用完从 sem_open() 获得的信号量后,您应该使用 sem_close()

关于c - 使用信号量同步来自不同进程的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55983461/

相关文章:

c - 无法理解使用 Turbo C 的 C 语言中错误的含义。我编写了这段代码

linux - Samba 4.5 - 错误(ldb): uncaught exception - operations error (password_hash. c:2816)

linux - 在 Qt 中保存/打开对话框本地化

java - 串行线程限制

c# - C#线程和表单: NotSupportedException - Use Control.调用吗?

Python 多处理信号量不工作

c - 如何在 OpenMP 中获取和释放锁

c - C中定时器滴答声的实现

c - 数组声明的非常奇怪的行为

linux - BASH:将curl参数作为$1变量传递