1

I'm using the gcc to compile this c program that just relies on 2 created thread, one to increment a counter, the second reads the counter and subtracts a random (0-9) value from the counter, and then displays the counter's value, using a Semaphore to access it. Still upon compilation I'm facing lots of ' Undefined reference to sem_init/sem_wait/sem_post/pthread_create/..etc' I don't know why although I associated them headers in my program.

I'm using 'gcc -o prog prog.c'to compile my program.

#include<semaphore.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int counter=0;
int run=1;
sem_t mutex;

void * increm();

void * decrem();


void main()
{       sem_t mutex;
    sem_init(&mutex,0,1);
    pthread_t t1,t2;
    pthread_create(&t1,NULL,increm,NULL);
    pthread_create(&t2,NULL,decrem,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
sem_destroy(&mutex);
}
void * increm()
{  while(run)
    {sem_wait(&mutex);
            counter++;
            sem_post(&mutex);
    }
    pthread_exit(NULL);
}

 void * decrem()
{ int i=25;

    while(i>0)
    {sem_wait(&mutex);
            counter-=(rand()%10);
           printf("Counter value : %d \n",counter);
            i--;
            sem_post(&mutex);
    }
    run=0;
    pthread_exit(NULL);
 }
mandez
  • 137
  • 1
  • 10
  • 1
    Note: `17:15: warning: declaration of ‘mutex’ shadows a global declaration [-Wshadow]` and I suspect after correct that issue and changing `void main` to `int main` and adding `-lpthread` to your compile string -- it will compile just fine. – David C. Rankin Jan 06 '18 at 18:25
  • Please explain in more detail which problems you have which cannot be solved by studying and applying the concepts from the link provided by VTT. – Yunnosch Jan 06 '18 at 18:28
  • @DavidC.Rankin Yes that was the actual problem, defining mutex again was a mistake of editing! plus added the flag -pthread into command line, all worked fine now. Thanks guys – mandez Jan 06 '18 at 20:37

1 Answers1

1

[...] upon compilation I'm facing lots of ' Undefined reference to sem_init/sem_wait/sem_post/pthread_create/..etc' I don't know why although I associated them headers in my program.

I'm using 'gcc -o prog prog.c'to compile my program.

With GCC, you should pass the -pthread option to gcc when you compile and when you link a program that uses pthreads functions:

gcc -pthread -o prog prog.c

At minimum, this will cause the needed library(-ies) to be included in the link, but in principle, it may have effects on code generation as well in some versions of GCC and on some platforms.

See also Significance of -pthread flag when compiling, Difference between -pthread and -lpthread while compiling, and many others.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157