新手Linux线程信号量问题,求大神指教
题目要求:利用线程信号量同步输出1+2+...+10(线程1),11+12+......+20(线程二)以此类推到91+92+....+100,下面是我的代码,但是结果错了,求大神帮我看看:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <sys/ipc.h>
#include <semaphore.h>
int sum1=0;int sum2=0;
sem_t sem1,sem2;
void *pthread1(void *arg)
{
int i;
int c;
for(c=0;c<5;c++)
{
sem_wait(&sem1);
for(i=1;i<=10;i++)
{
sum1+=i;
}
sem_post(&sem2);
printf("pthread1 num:%d\n",sum1);
}
}
void *pthread2(void *arg)
{
int j;
int a;
for(a=0;a<5;a++)
{
sem_wait(&sem2);
for(j=1;j<20;j++)
{
sum2+=j;
}
sem_post(&sem1);
printf("pthread2 num:%d\n",(sum2-sum1));
}
}
int main(int argc,char *argv[])
{
pthread_t tid1,tid2;
int ret;
ret=sem_init(&sem1,0,1);
ret=sem_init(&sem2,0,1);
if(ret!=0)
{
perror("sem_init");
exit(-1);
}
ret=pthread_create(&tid1,NULL,(void *)pthread1,NULL);
if(ret!=0)
{
perror("pthread cread1");
exit(-1);
}
ret=pthread_create(&tid2,NULL,(void *)pthread2,NULL);
if(ret!=0)
{
perror("pthread cread2");
exit(-1);
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
exit(0);
}