linux子线程运行的函数_linux下的多线程,在子线程中调用scanf()函数程序就终止了。。为什么?...

问题解决了.

我在main最后加了四句话,附上完整的程序:

#include

#include

#include

#include

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]'z')&&(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;

}


版权声明:本文为weixin_30195669原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。