Hi,
I'm debugging a program using pthreads for a class I have to solve a producer consumer problem. What I'm running into is that I get an error saying that I have a undefined reference to the create a join functions. After that I put the initialization functions in but now I get the error that none of them were declared within the scope, and removing the using namespace std does not help. I have already included pthread.h and have only made global the variables that need to be shared. I have check with the text book and I'm doing everything that he did (although he leaves out lines in favor of a single comment saying what was done a lot) and can't find and problems online ether. What should I do to fix this error. Here's my code:
#include <iostream>
#include <pthread.h>
#include <time.h>
#include <queue>
using namespace std;
#define NUM_THRDS 128
#define MAX 64
queue<int> q;
int inq=0;
pthread_mutex_t q_mutex;
int num_items=0;
void *produce(void *);
void *consume(void *);
int main()
{
pthread_t thrds [NUM_THRDS];
pthread_attr_t attr;
time_t sec,sec2;
pthread_init();
ptread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&q_mutex,NULL);
sec = time(NULL);
cout<<sec<<endl;
for(int i=0; i<NUM_THRDS; i++)
{
if(i%2==0)
pthread_create(&thrds[i], &attr, produce, NULL);
else
pthread_create(&thrds[i], &attr, consume, NULL);
}
for(int i=0; i<NUM_THRDS; i++)
pthread_join(thrds[i],NULL);
sec2=time(NULL);
cout<<sec2<<endl<<"Total time "<<sec2-sec<<" seconds."<<endl;
cout<<endl<<endl;
return 0;
}
void *produce(void * n)
{
while(true)
{
pthread_mutex_lock(&q_mutex);
if(num_items >= 1000)
{
pthread_mutex_unlock(&q_mutex);
pthread_exit(0);
}
if(inq < MAX)
{
q.push(1);
inq++;
num_items++;
}
pthread_mutex_unlock(&q_mutex);
}
}
void *consume(void * n)
{
while(true)
{
pthread_mutex_lock(&q_mutex);
if(num_items >= 1000 && inq == 0)
{
pthread_mutex_unlock(&q_mutex);
pthread_exit(0);
}
if(inq > 0)
{
q.pop();
inq--;
}
pthread_mutex_unlock(&q_mutex);
}
}
The last time I compiled I got the following error (copy pasted out of the bash terminal):
queue_program.cpp: In function ‘int main()’: queue_program.cpp:23: error: ‘pthread_init’ was not declared in this scope queue_program.cpp:24: error: ‘ptread_attr_init’ was not declared in this scope
Note: please don't leave comment telling me that the progrm does nothing. The point of this homework was to implement producer and consumer threads to a queue and provide mutex, not to do anything with what is actually going in or out of the queue.