【问题标题】:Synchronize threads from different processes using semaphore使用信号量同步来自不同进程的线程
【发布时间】:2019-05-04 14:20:21
【问题描述】:

我在 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;
}

【问题讨论】:

    标签: c linux multithreading semaphore


    【解决方案1】:

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

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

    【讨论】:

    • 我把它改成 sem_close(),但同样的事情发生了。
    • 现在你的下一个问题是第一个运行function1()的线程在调用sem_wait()时不会阻塞,因为当你创建信号量时,它的初始值为1。sem_wait()会递减为 0 并立即继续。如果创建初始值为 0 的信号量,则对 sem_wait() 的第一次调用将阻塞,直到其中一个 sem_post() 方法在 function2() 中触发。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 2017-08-31
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    相关资源
    最近更新 更多