- 论坛徽章:
- 0
|
问题解决了.
我在main最后加了四句话,附上完整的程序:
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h>
sem_t s;
sem_t p;
sem_t c;
int in=0;
int out=0;
char buffer[10];
pthread_mutex_t print_m;
void pp()
{
int i=0;
printf("buffer: ");
for(i;i!=strlen(buffer);i++)
printf("%c ",buffer);
printf("in=%d out=%d\n",in,out);
}
void* producer(char *a)
{
pthread_mutex_lock(&print_m);
printf("%s is running\n",a);
pthread_mutex_unlock(&print_m);
while(1)
{
sem_wait(&p);
sem_wait(&s);
pthread_mutex_lock(&print_m);
printf("%s Produced:",a);
//setbuf(stdin,NULL);
scanf("%c",&buffer[in]);
while ((buffer[in]<'a'||buffer[in]>'z')&&(buffer[in]<'A'||buffer[in]>'Z'))
scanf("%c",&buffer[in]);
in=(in+1)%10;
pp();
printf("\n");
pthread_mutex_unlock(&print_m);
sem_post(&c);
sem_post(&s);
}
}
void* consumer(char *a)
{
pthread_mutex_lock(&print_m);
printf("%s is running\n",a);
pthread_mutex_unlock(&print_m);
while(1)
{
sem_wait(&c);
sem_wait(&s);
pthread_mutex_lock(&print_m);
printf("%s Consumed:%c\n",a,buffer[out]);
out=(out+1)%10;
pp();
printf("\n");
pthread_mutex_unlock(&print_m);
sem_post(&p);
sem_post(&s);
}
}
int main()
{
sem_init(&s,1,1);
sem_init(&p,0,10);
sem_init(&c,0,0);
pthread_mutex_init(&print_m,NULL);
pthread_t p_1;
pthread_t p_2;
pthread_t c_1;
pthread_t c_2;
pthread_create(&c_1,NULL,(void*)consumer,"C1");
pthread_create(&p_1,NULL,(void*)producer,"P1");
pthread_create(&c_2,NULL,(void*)consumer,"C2");
pthread_create(&p_2,NULL,(void*)producer,"P2");
pthread_join(p_1,NULL);
pthread_join(p_2,NULL);
pthread_join(c_1,NULL);
pthread_join(c_2,NULL);
return 0;
} |
|