2015-10-05 96 views
1

所以我有两个线程和互斥体的生产者和消费者问题有点麻烦。我想要做的是让制作人用10 1填充一个数组。然后消费者消费每个1并使其为0.这种填充和排空重复10次。以下是我迄今为止,但它卡住在第一个周期:生产者和消费者的互斥和线程编程

#include <stdio.h> 
#include <pthread.h> 
#define N 10 

pthread_mutex_t mut; 
pthread_cond_t condc,condp; 
int queue[N]; 
int buffer; 

void* prod() { 
    int i; 
    for(i = 0; i<10; i++) { 
     pthread_mutex_lock(&mut); 
     while(queue[N] != 0) { 
      pthread_cond_wait(&condp, &mut); 
     } 
     int k = 0; 
     for(k=0; k<10; k++) { 
      queue[k] = 1; 
     } 

     pthread_cond_signal(&condc); 
     pthread_mutex_unlock(&mut); 
     printf("\nproduced\n"); 
    } 
    pthread_exit(0); 
} 

void* cons() { 
    int i; 
    for(i = 0; i<10; i++) { 
     pthread_mutex_lock(&mut); 
     while(queue[N] == 0) { 
      pthread_cond_wait(&condc, &mut); 
     } 
     int k = 0; 
     for(k=0; k<10; k++) { 
      queue[k] = 0; 
     } 
     pthread_cond_signal(&condp); 
     pthread_mutex_unlock(&mut); 
     printf("\nconsumed\n"); 
    } 
    pthread_exit(0); 
} 

main() { 
    pthread_t producer, consumer; 
    pthread_mutex_init(&mut, 0); 
    pthread_cond_init(&condc, 0); 
    pthread_cond_init(&condp, 0); 
    pthread_create(&consumer,NULL,&cons, NULL); 
    pthread_create(&producer,NULL,&prod, NULL); 
    pthread_join(producer,0); 
    pthread_join(consumer,0); 
    pthread_cond_destroy(&condc); 
    pthread_cond_destroy(&condp); 
    pthread_mutex_destroy(&mut); 

    return 0; 
} 
+0

'queue [N]'是什么意思? –

+0

它只是填满了数组 – samuelk71

+1

我的意思是你为什么要访问数组之外​​的内存? –

回答

2

你没有,你开始阅读之前的queue成员初始化任何特定的值。另外,你读queue超出范围 - 它有十个值,但你读了第十一个值。最后,你永远不会改变你读的价值 - 你设定了前十个值,你永远不会看。