成员变量得到一个随机值,即使我在构造函数中初始化它 - 为什么?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了成员变量得到一个随机值,即使我在构造函数中初始化它 - 为什么?相关的知识,希望对你有一定的参考价值。
我正在尝试使用我的老师和pthreads库提供的Monitor类来编写经典的生产者 - 消费者程序。我认为我的简单算法背后有逻辑,但为了使它工作,我需要跟踪缓冲区中当前有多少元素。我不知道为什么,但负责该值的变量是随机值,即使我在构造函数中将它(以及其他2个变量)初始化为零。谁能指出我犯的错误? (来自老师的监控库提供了enter()和leave()函数,确保只有一个线程访问它们和Condition类,它提供条件变量,你可以执行wait()和signal() - 就像在正常的monitor中一样。)
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
答案
我的错误是将第4个参数传递给pthread_create作为引用 - 当它已经是指针时。
所以我应该在没有这样的情况下传递它:
pthread_create (&thread1_id, NULL, &producer, just_buffer);
或者只是定义我的类的普通对象而不是像这样的指针:
MyBuffer just_buffer;
以上是关于成员变量得到一个随机值,即使我在构造函数中初始化它 - 为什么?的主要内容,如果未能解决你的问题,请参考以下文章