LINUX中线程同步信号量问题
我在主线程中创建了新线程,建立了两个信号量,希望这两个线程能够同步工作,但是实验结果中,经常出现信号量丢失的问题,希望高手给我指点。源程序:#include<stdio....
我在主线程中创建了新线程,建立了两个信号量,希望这两个线程能够同步工作,但是实验结果中,经常出现信号量丢失的问题,希望高手给我指点。
源程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem1,sem2;
void fun(void *arg)
{
printf("fall asleep\n");
sem_wait(&sem1);printf(" 1\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 3\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 5\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 7\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 9\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 11\n");sem_post(&sem2);
exit(EXIT_FAILURE);
}
int main()
{
pthread_t thread;
int arg=1,res;
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
res=pthread_create(&thread,PTHREAD_CREATE_JOINABLE,(void*)fun,NULL);
if(res)
{
printf("pthread_create error!\n");
exit(EXIT_FAILURE);
}
sleep(1);
sem_post(&sem1);sem_wait(&sem2);printf("2\n");
sem_post(&sem1);sem_wait(&sem2);printf("4\n");
sem_post(&sem1);sem_wait(&sem2);printf("6\n");
sem_post(&sem1);sem_wait(&sem2);printf("8\n");
sem_post(&sem1);sem_wait(&sem2);printf("10\n");
sem_post(&sem1);sem_wait(&sem2);printf("12\n");
pthread_join(thread,NULL);
return 0;
}
我的实验结果,有时候能够顺利打印出1~12,可是会出现12漏掉的情况,就是1~11,请高手指点原因。 展开
源程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem1,sem2;
void fun(void *arg)
{
printf("fall asleep\n");
sem_wait(&sem1);printf(" 1\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 3\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 5\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 7\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 9\n");sem_post(&sem2);
sem_wait(&sem1);printf(" 11\n");sem_post(&sem2);
exit(EXIT_FAILURE);
}
int main()
{
pthread_t thread;
int arg=1,res;
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
res=pthread_create(&thread,PTHREAD_CREATE_JOINABLE,(void*)fun,NULL);
if(res)
{
printf("pthread_create error!\n");
exit(EXIT_FAILURE);
}
sleep(1);
sem_post(&sem1);sem_wait(&sem2);printf("2\n");
sem_post(&sem1);sem_wait(&sem2);printf("4\n");
sem_post(&sem1);sem_wait(&sem2);printf("6\n");
sem_post(&sem1);sem_wait(&sem2);printf("8\n");
sem_post(&sem1);sem_wait(&sem2);printf("10\n");
sem_post(&sem1);sem_wait(&sem2);printf("12\n");
pthread_join(thread,NULL);
return 0;
}
我的实验结果,有时候能够顺利打印出1~12,可是会出现12漏掉的情况,就是1~11,请高手指点原因。 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询