getting semaphores to work
Code:
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void *producer(void *ptr);
void handler(void *ptr);
sem_t mutex;
int counter=0;
int main()
{
int i; int numThreads=1;
pthread_t *myThreads;
myThreads=new pthread_t [numThreads];
sem_init(&mutex, 0, 1);
srand((unsigned)time(NULL));
for(i=0; i<numThreads; i++)
{
pthread_create(&myThreads[i],NULL,producer,(void *)i);
}
for(i=0; i<numThreads; i++)
{
pthread_join(myThreads[i],NULL);
}
sem_destroy(&mutex);
return(0);
}
void *producer(void *ptr)
{
int x;
int b;
b = (rand() & 255);
for(x=0; x<b; x++)
{
if( (rand() & 1) == 0)
{
handler(ptr);
}
}
return 0;
}
void handler(void *ptr)
{
sem_wait(&mutex);
counter++;
cout<<"Thread "<<ptr<<" New Counter Value: "<<counter<<endl;
sem_post(&mutex);
}
I am trying to compile the following code under NetBSD, using the g++ compiler. Get the following errors:
/var/tmp//ccpSzRS9.o(.text+0x39): In function `main':
: undefined reference to `sem_init'
/var/tmp//ccpSzRS9.o(.text+0xb1): In function `main':
: undefined reference to `pthread_join'
/var/tmp//ccpSzRS9.o(.text+0xc8): In function `main':
: undefined reference to `sem_destroy'
/var/tmp//ccpSzRS9.o(.text+0x135): In function `handler(void*)':
: undefined reference to `sem_wait'
/var/tmp//ccpSzRS9.o(.text+0x1a3): In function `handler(void*)':
: undefined reference to `sem_post'
Any ideas on how to fix these errors? I think it something with the libraries.