Hello Members,

I want to write a C program which creates two threads and uses a semaphore (as a critical section) to sleep for 1 second and then terminate. I am having a hard time with some of the C Syntax for semaphores. Is it possible to post an example code for this problem?

Kindly let me know.

Thank you!

Recommended Answers

All 8 Replies

Instead of someone posting an example you should post what you have tried.

Hello Dragon,

Makes sense! Following is an example code that I found online which is making some sense to me:

/* Includes */
#include <unistd.h>     /* Symbolic Constants */
#include <sys/types.h>  /* Primitive System Data Types */ 
#include <errno.h>      /* Errors */
#include <stdio.h>      /* Input/Output */
#include <stdlib.h>     /* General Utilities */
#include <pthread.h>    /* POSIX Threads */
#include <string.h>     /* String handling */
#include <semaphore.h>  /* Semaphore */

/* prototype for thread routine */
void handler ( void *ptr );

/* global vars */
/* semaphores are declared global so they can be accessed 
   in main() and in thread routine,
   here, the semaphore is used as a mutex */
sem_t mutex;
int counter; /* shared variable */

int main()
{
    int i[2];
    pthread_t thread_a;
    pthread_t thread_b;
    
    i[0] = 0; /* argument to threads */
    i[1] = 1;
    
    sem_init(&mutex, 0, 1);      /* initialize mutex to 1 - binary semaphore */
                                 /* second param = 0 - semaphore is local */
                                 
    /* Note: you can check if thread has been successfully created by checking return value of
       pthread_create */                                 
    pthread_create (&thread_a, NULL, (void *) &handler, (void *) &i[0]);
    pthread_create (&thread_b, NULL, (void *) &handler, (void *) &i[1]);
    
    pthread_join(thread_a, NULL);
    pthread_join(thread_b, NULL);

    sem_destroy(&mutex); /* destroy semaphore */
    /* exit */  
    exit(0);
} /* main() */

void handler ( void *ptr )
{
    int x; 
    x = *((int *) ptr);
    printf("Thread %d: Waiting to enter critical region...\n", x);
    sem_wait(&mutex);       /* down semaphore */
    /* START CRITICAL REGION */
    printf("Thread %d: Now in critical region...\n", x);
    printf("Thread %d: Counter Value: %d\n", x, counter);
    printf("Thread %d: Incrementing Counter...\n", x);
    counter++;
    printf("Thread %d: New Counter Value: %d\n", x, counter);
    printf("Thread %d: Exiting critical region...\n", x);
    /* END CRITICAL REGION */    
    sem_post(&mutex);       /* up semaphore */
    
    pthread_exit(0); /* exit thread */
}

When I tried to compile using the following command:

gcc filename.c -lpthread

I get the following errors:

Undefined                       first referenced
 symbol                             in file
sem_destroy                         /var/tmp//ccUFqVaE.o
sem_init                            /var/tmp//ccUFqVaE.o
sem_post                            /var/tmp//ccUFqVaE.o
sem_wait                            /var/tmp//ccUFqVaE.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status

Once I am able to run, I think I will understand the program better. I would be grateful for any help.

Thank you!

> gcc filename.c -lpthread
is not enough. You also need -lrt

Hello Neza,

It works now. Could you tell me what does -lrt do?

Thank you!

It links in the librt.so, the library which provides (among other things) implementation of the sem_* functions. Ask me not why this library is called rt; however, see the Linking section of a sem_overview manpage.
PS: it is important to realize that sem family is not related to pthread family whatsoever. The fact that posix semaphores, pthreads (as well as System V primitives) coexist peacefully in the same system is one of the marvels of unix.

Hello Neza,

That was very helpful!

Thank you!

gcc -pthread filename.c
is also enough.

commented: Replying to threads that are 6 years old is not productive. -3

Your post is very helpful,,,Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.