成员变量得到一个随机值,即使我在构造函数中初始化它 - 为什么?

时间:2017-12-17 11:00:51

标签: c++ synchronization pthreads monitor

我试图使用我的老师和pthreads库提供的Monitor类来编写经典的生产者 - 消费者程序。我认为我的简单算法背后有逻辑,但为了使它能够工作,我需要跟踪缓冲区中当前有多少元素。我不知道为什么,但负责该值的变量是随机值,即使我在构造函数中将它(以及其他2个变量)初始化为零。谁能指出我犯的错误?  (来自teacher的监视库提供了enter()和leave()函数,这些函数确保只有一个线程正在访问它们之间的数据和Condition类,它提供了可以执行wait()和signal()的条件变量 - 就像在普通{ {3}}。)

main.cpp中:

#include <stdio.h>
#include <pthread.h>
#include "mybuffer.h"

void* client (void* parameters)
{
  MyBuffer *p = (MyBuffer *) parameters;
  char whatsinthebox;
  int loop_counter = 0;
  while(loop_counter < 5) {
    printf("Client loop nr: %d\n",loop_counter);
    whatsinthebox = p->Pop();
    printf("Product recieved: %c\n", whatsinthebox);
    sleep(5);
    loop_counter++;

  }
}

void* producer (void* parameters)
{
  MyBuffer *p = (MyBuffer *) parameters;
  int loop_counter = 0;
  char product = 'X';
  while(loop_counter<20) {
    printf("Producer loop nr: %d\n",loop_counter);
    p->Push(product);
    printf("Product inserted: %c\n", product);
    sleep(1);
    loop_counter++;
  }
}


int main()
{
  MyBuffer *just_buffer = new MyBuffer();
  pthread_t thread1_id;
  pthread_t thread2_id;

  pthread_create (&thread1_id, NULL, &producer, &just_buffer);
  pthread_create (&thread2_id, NULL, &client, &just_buffer);

  pthread_join (thread1_id, NULL);
  pthread_join (thread2_id, NULL);

  delete just_buffer;
  return 0;
}

mybuffer.h:

#ifndef MYBUFFER_H
#define MYBUFFER_H

#define MAX_ELEMENTS 9
#define BUFFER_SIZE (MAX_ELEMENTS+1)

#include "monitor.h"

class MyBuffer: public Monitor
{
private:

  int data_in, data_out, elements_count;
  char data[BUFFER_SIZE];
  Condition full, empty;

public:

  MyBuffer ()
  {
    enter();
    data_in = data_out = 0;
    elements_count = 0;
    leave();
  }

  int Push(char c)
  {
    enter();
    printf("Elements count before conditon in Push: %d\n",elements_count);
    printf("data_in before conditon in Push: %d\n",data_in);
    printf("data_out count before conditon in Push: %d\n",data_out);
    if (elements_count == MAX_ELEMENTS)
      wait(full); // queue full - can't push
    data[data_in] = c;
    data_in = (data_in + 1) % BUFFER_SIZE;
    elements_count++;
    if (elements_count == 1)
      signal(empty);
    leave();
    return 0; // no errors
  }

  char Pop()
  {
    char value;
    enter();    
    if (elements_count == 0)
      wait(empty); // queue empty - nothing to pop
    value = data[data_out];
    data_out = (data_out + 1) % BUFFER_SIZE;
    elements_count--;
    if (elements_count == MAX_ELEMENTS - 1)
      signal(full);
    leave();
    return value;
  }
};

#endif

1 个答案:

答案 0 :(得分:0)

我的错误是将第4个参数传递给pthread_create作为引用 - 当它已经是指针时。

所以我应该在没有&amp; amp;像这样:

pthread_create (&thread1_id, NULL, &producer, just_buffer);

或者只是定义我的类的普通对象而不是像这样的指针:

MyBuffer just_buffer;