0

所以我有了这个生成器,应该输出的第一个数字是 1804289383。

但是,我得到的数字是 134519520,有时最后几位数字会有所不同,但通常在这个数字附近。

知道为什么吗?我有类似的代码打印出所需的数字,但这不起作用。

#include <stdio.h>
#include <pthread.h>
#define MAX_NUM 10
#define MAX_RAND_NUM 100
#define SIZE 10

pthread_mutex_t the_mutex;
pthread_cond_t cond;
int buffer[SIZE];
int num_of_items = 0;

void *producer(void *ptr)
{   
    int i  = 0;
    int rand_num = 0;
    int rear = 0;   
    srandom((unsigned int)0);


        rand_num = random();
    pthread_mutex_lock(&the_mutex);
    while (num_of_items = SIZE) {
        pthread_cond_wait(&cond,&the_mutex);
    }//end of while loop
      buffer[rear] = rand_num;
      rear = (rear + 1) % SIZE;
      num_of_items +=1;
      printf("Producer on loop %d it stored %d \n",i,rand_num);
      pthread_cond_signal(&cond);
      pthread_mutex_unlock(&the_mutex);

        pthread_exit(0);
}

void *consumer(void *ptr)
{       int i  = 0;
        int rand_num = 0;
    int front = 0;

    pthread_mutex_lock(&the_mutex);
        while (num_of_items == 0) pthread_cond_wait(&cond,&the_mutex);
            printf("Consumer on loop %d it stored %d \n",i,buffer);
        //buffer[0] = 0;
        front = (front + 1) % SIZE;
        num_of_items -= 1;
            pthread_cond_signal(&cond);
            pthread_mutex_unlock(&the_mutex);

            pthread_exit(0);
}

int main(int argc, char **argv)
{
   pthread_t pro,con;
   pthread_mutex_init(&the_mutex,0);
   pthread_cond_init(&cond,0);

   pthread_create(&con,0,consumer,0);
   pthread_create(&pro,0,producer,0);
   pthread_join(pro,0);
   pthread_join(con,0);
   pthread_cond_destroy(&cond);

   pthread_mutex_destroy(&the_mutex);
}
4

1 回答 1

2

这是问题所在:

printf("Consumer on loop %d it stored %d \n",i,buffer);

buffer衰减为指针,但您试图将其打印为int. 你得到的那个大数字是地址的整数表示。也许你打算做些buffer[i]什么。

这看起来也有点可疑:

while (num_of_items = SIZE)

可能这应该是一个==.

如果您的编译器没有就这两件事向您发出警告,您也许应该寻找更好的,或者提高您的警告级别。

于 2013-11-05T01:53:11.073 回答