所以我有了这个生成器,应该输出的第一个数字是 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);
}