【问题标题】:Number generator not printing out expected first number in C数字生成器未打印出 C 中预期的第一个数字
【发布时间】:2013-11-05 01:33:53
【问题描述】:

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

【问题讨论】:

  • 恐怕从上面的代码中看不出为什么你会特别期待 1804289383。您能否提供有关您为什么需要/期望该特定数字的更多信息?
  • 我正在制作一个生成器,它要求它是我分配的第一个数字。现在,当我执行这段代码时,程序只是挂起,我一直无法弄清楚原因。
  • 一方面,循环“while (num_of_items = SIZE)”将永远循环——您是在分配,而不是比较值。

标签: c multithreading numbers pthreads generator


【解决方案1】:

问题来了:

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

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

这看起来也有点可疑:

while (num_of_items = SIZE)

可能应该是==

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

【讨论】:

  • 我发誓,这总是一个菜鸟的错误。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
相关资源
最近更新 更多