John John - 2 months ago 14
C++ Question

Error when trying to wait on semaphore

I have a class which contains a semaphore. On execution of the classes run method. It creates a thread and passes a function and an object pointer of my class. The function then tried to access the object and the semaphore inside of it and call wait. But the compiler is not letting me do it.

Error:

myNode.cpp: In function 'void* MyProjectGraph::compute(void*)':
myNode.cpp:70: error: request for member 'sem' in 'node->MyProjectGraph::MyNode::in.std::vector<_Tp, _Alloc>::operator[] [with _Tp = MyProjectGraph::MyEdge*, _Alloc = std::allocator<MyProjectGraph::MyEdge*>](((long unsigned int)i))', which is of non-class type 'MyProjectGraph::MyEdge*'
myNode.cpp:82: error: request for member 'sem' in 'node->MyProjectGraph::MyNode::in.std::vector<_Tp, _Alloc>::operator[] [with _Tp = MyProjectGraph::MyEdge*, _Alloc = std::allocator<MyProjectGraph::MyEdge*>](((long unsigned int)i))', which is of non-class type 'MyProjectGraph::MyEdge*'
myNode.cpp:87: error: request for member 'sem' in 'node->MyProjectGraph::MyNode::out.std::vector<_Tp, _Alloc>::operator[] [with _Tp = MyProjectGraph::MyEdge*, _Alloc = std::allocator<MyProjectGraph::MyEdge*>](((long unsigned int)i))', which is of non-class type 'MyProjectGraph::MyEdge*'
make: *** [myNode.o] Error 1


Method passed in on pthread_create

void *compute(void *ptr){
MyNode* node = (MyNode*)ptr;
time_t end;

cout<<"Node Running: "<<node->ltr<<endl;

//wait on all incoming edges
for(int i = 0; i < node->in.size();i++){
sem_wait(&(node->in[i].sem));
//node->in[i].edgeWait();
}

sleep(node->time);
sem_wait(&count_sem);
graphCount += node->value;
sem_post(&count_sem);
time(&end);

//destory dependent semaphores
for(int i = 0; i < node->in.size();i++){
sem_destroy(&(node->in[i].sem));
}

//post all outgoing edges
for(int i = 0; i < node->out.size();i++){
sem_post(&(node->out[i].sem));
//node->out[i].edgePost();
}

printf("Node %c computed a value of %d after %.2lf second.",node->ltr,node->value,difftime(end,start));
pthread_exit(NULL);
return 0;
}


Basic design of node and edge classes

class MyNode{
public:
int tid;
int value;
int time;
char ltr;

pthread_t thread;

std::vector<MyEdge*> in;
std::vector<MyEdge*> out;

MyNode( );
MyNode(char ltr, int val, int time);
void addInEdge(MyEdge* edge);
void addOutEdge(MyEdge* edge);
void run( );
void signalEdges( );
void waitEdges( ); //Implementation is not known atm
void toString( );
};

class MyEdge{
public:
MyNode* in;
MyNode* out;

sem_t sem;

MyEdge(int init, MyNode* in, MyNode* out);
int edgeWait( );
int edgePost( );
};
}

Answer
  sem_wait(&(node->in[i].sem));

Your in class member is a:

  std::vector<MyEdge*> in;

Therefore, in[i] is a MyEdge *.

As such, to access its sem member, this should be:

  sem_wait(&(node->in[i]->sem));

The other compilation errors is the same problem.

Comments