필자는 선생님과 pthreads 라이브러리에서 제공하는 Monitor 클래스를 사용하여 고전적인 프로듀서 - 소비자 프로그램을 작성하려고합니다. 내 간단한 알고리즘 뒤에 논리를 가지고 있다고 생각하지만, 작동하려면 버퍼에 현재 얼마나 많은 요소가 있는지 추적해야합니다. 왜 그런지는 모르겠지만 그 값을 책임지는 변수는 무작위 값을 얻고있다. 심지어 다른 변수와 함께 2를 생성자에서 0으로 초기화한다. 누구든지 실수를 지적 할 수 있을까요? (선생님의 모니터 라이브러리는 하나의 스레드 만 그들 사이의 데이터에 액세스하도록하는 enter() 및 leave() 함수를 제공합니다.이 클래스는 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
내 오류가 네번째 인수를 전달 있었다
그래서 나는이 같은 &없이 passi 중 하나를해야 참조로 pthread_create - 이미 포인터 였을 때. – Soonmoon