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!

Dani AI

Generated

If your goal is simply to serialize a short critical section, an unnamed POSIX semaphore works fine. Initialize it with count 1, have each thread sem_wait() before entering the region, sleep for 1 second inside that region (to make the serialization obvious), then sem_post() and exit. Prefer compiling with -pthread rather than -lpthread; -pthread also enables the right thread-safety flags in addition to linking the proper libraries. See the relevant manuals for details: pthread_create(3), sem_init(3).

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

static sem_t gate;

static void *worker(void *arg) {
    const char *name = (const char *)arg;
    if (sem_wait(&gate) != 0) { perror("sem_wait"); return (void *)1; }
    printf("%s: entered critical section\n", name);
    sleep(1);  /* simulate work while holding the semaphore */
    printf("%s: leaving\n", name);
    if (sem_post(&gate) != 0) perror("sem_post");
    return NULL;
}

int main(void) {
    if (sem_init(&gate, 0, 1) != 0) { perror("sem_init"); return 1; }

    pthread_t t1, t2;
    pthread_create(&t1, NULL, worker, "T1");
    pthread_create(&t2, NULL, worker, "T2");
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    sem_destroy(&gate);
    return 0;
}

Build with:

gcc -pthread sem_demo.c -o sem_demo

Notes: keeping sleep(1) inside the critical section forces strict one-at-a-time behavior. If you only need to protect a shared update, move the sleep outside or consider a pthread_mutex_t for a lighter-weight mutex-only primitive.

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 , 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.