我在 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/