所以我有这个发生器,应该输出的第一个数字是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);
}
答案 0 :(得分:2)
问题在于:
printf("Consumer on loop %d it stored %d \n",i,buffer);
buffer
衰减到指针,但您尝试将其打印为int
。你得到的那个大数字是地址的整数表示。也许你打算做buffer[i]
或其他什么。
这看起来也很可疑:
while (num_of_items = SIZE)
可能应该是==
。
如果你的编译器没有警告你这两件事,你应该寻找更好的,或者提高你的警告水平。