#include <pthread.h>
class Stack{
public:
Stack();
~Stack();
int pop();
void push(int);
private:
static const int STACKSIZE;
int elem[STACKSIZE];
int top;
pthread_mutex_t mutex;
pthread_cond_t notfull, notempty;
};
#include "stack.h"
#include <pthread.h>
Stack::Stack():
top(-1),
mutex(PTHREAD_MUTEX_INITIALIZER),
notfull(PTHREAD_COND_INITIALIZER),
notempty(PTHREAD_COND_INITIALIZER)
{}
/*
same effect as
lock
while (isfull());
doit;
unlock
*/
const int Stack::STACKSIZE = 10;
void Stack::push(int v) {
pthread_mutex_lock(&mutex);
while (top == STACKSIZE) {//full?
pthread_cond_wait(¬full, &mutex);
}
this->elem[++top] = v;
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(¬empty);
}
int Stack::pop() {
pthread_mutex_lock(&mutex);
while (top == -1) {//empty?
pthread_cond_wait(¬empty, &mutex);
}
int retval = elem[top--];
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(¬full);
return retval;
}
elem定义成public
没有对象可以直接用吗!!!!!,要么你改成static要么改成全局的。
对于STACKSIZE的定义,你这样写试一下
private:
static const int STACKSIZE=10;
int elem[STACKSIZE];
int top;
pthread_mutex_t mutex;
pthread_cond_t notfull, notempty;
再把后面定义的const int Stack::STACKSIZE = 10;注释掉