Skip to content

Instantly share code, notes, and snippets.

@tausen
Created December 11, 2012 20:30
Show Gist options
  • Save tausen/4261887 to your computer and use it in GitHub Desktop.
Save tausen/4261887 to your computer and use it in GitHub Desktop.
pthread, sem_wait, sem_post example
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
sem_t semaphore;
void threadfunc() {
while (1) {
sem_wait(&semaphore);
printf("Hello from da thread!\n");
sem_post(&semaphore);
sleep(1);
}
}
int main(void) {
// initialize semaphore, only to be used with threads in this process, set value to 1
sem_init(&semaphore, 0, 1);
pthread_t *mythread;
mythread = (pthread_t *)malloc(sizeof(*mythread));
// start the thread
printf("Starting thread, semaphore is unlocked.\n");
pthread_create(mythread, NULL, (void*)threadfunc, NULL);
getchar();
sem_wait(&semaphore);
printf("Semaphore locked.\n");
// do stuff with whatever is shared between threads
getchar();
printf("Semaphore unlocked.\n");
sem_post(&semaphore);
getchar();
return 0;
}
@Congee
Copy link

Congee commented Jan 28, 2018

Great simple example. Remember to free your mythread variable. You actually don't need to allocate mythread on heap, it's just usually of long long int type, which requires 8bytes memory.

@Coarist
Copy link

Coarist commented Mar 1, 2019

Thank you for giving this code to demonstrate the mechanics of pthread and semaphore.

In main() there are three getchar(); lines. When building my code I commented out the first of these three lines to get a clearer idea of what is happening.

Building the C code (not C++) for Windows these header files are included additionally:
#include <io.h> **// Windows VisualStudio. For Linux #include <unistd.h>**
#include <ddkernel.h> **// Windows VisualStudio to use Sleep()**

POSIX pthreads on Windows we can add the following package to the build. I assume that on Linux there will be equivalent additional package readily available to us without changing our C source code.
ftp://sourceware.org/pub/pthreads-win32/dll-latest
In the package .h and .lib are to be included in the VS project. After building the .exe Windows console application execute it from the same directory as the corresponding .dll in this package. There are a few to choose from.

Threading and interprocess communication have a wide number of schemes from which we can select. Of these tausen's code given here demonstrated pthreads and semaphores.

@sahin52
Copy link

sahin52 commented May 5, 2021

I needed to write sem_post before sem_wait in order to make it work.

@arshadmustafa34
Copy link

interesting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment