-
-
Save tausen/4261887 to your computer and use it in GitHub Desktop.
#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; | |
} |
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.
I needed to write sem_post before sem_wait in order to make it work.
interesting
Great simple example. Remember to free your
mythread
variable. You actually don't need to allocatemythread
on heap, it's just usually oflong long int
type, which requires 8bytes memory.