Last active
September 4, 2019 10:22
-
-
Save sahib/1712515 to your computer and use it in GitHub Desktop.
A rather primitive Semaphore implementation in C using pthreads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
/* Stupid implementation of C semaphores with pthreads. | |
* Used as mutex for counting a variable below. | |
* | |
* compile with: | |
* | |
* cc semaphor.c -o sam -lpthread -Wall -Wextra -std=c99 -Os | |
* | |
*/ | |
typedef struct { | |
pthread_cond_t cond; | |
pthread_mutex_t mtx; | |
volatile unsigned N; | |
} Sam; | |
//////////////////////////////////////// | |
#define SAM_INIT(n) \ | |
{ \ | |
.cond = PTHREAD_COND_INITIALIZER, \ | |
.mtx = PTHREAD_MUTEX_INITIALIZER, \ | |
.N = n \ | |
}; | |
//////////////////////////////////////// | |
void sam_init(Sam * ps, int N) { | |
pthread_mutex_init(&ps->mtx,NULL); | |
pthread_cond_init(&ps->cond,NULL); | |
ps->N = N; | |
} | |
//////////////////////////////////////// | |
void sam_destroy(Sam * ps) { | |
pthread_cond_destroy(&ps->cond); | |
pthread_mutex_destroy(&ps->mtx); | |
} | |
//////////////////////////////////////// | |
void sam_acquire(Sam * ps) { | |
pthread_mutex_lock(&ps->mtx); | |
while(ps->N == 0) { | |
pthread_cond_wait(&ps->cond,&ps->mtx); | |
} | |
--(ps->N); | |
pthread_mutex_unlock(&ps->mtx); | |
} | |
//////////////////////////////////////// | |
void sam_release(Sam * ps) { | |
pthread_mutex_lock(&ps->mtx); | |
++(ps->N); | |
pthread_mutex_unlock(&ps->mtx); | |
pthread_cond_signal(&ps->cond); | |
} | |
//////////////////////////////////////// | |
//////////////////////////////////////// | |
//////////////////////////////////////// | |
static const int N = 20; | |
static const int Z = 200000; | |
static int COUNTER = 0; | |
void *thread_func(void *semaphore) { | |
Sam * mumm = semaphore; | |
sam_acquire(mumm); | |
for(int i = 0; i < Z; i++) { | |
++COUNTER; | |
} | |
sam_release(mumm); | |
return NULL; | |
} | |
//////////////////////////////////////// | |
int main(void) { | |
Sam Mumm = SAM_INIT(1); | |
pthread_t threads[N]; | |
for(int i = 0; i < N; i++) { | |
pthread_create(&threads[i],NULL,thread_func,&Mumm); | |
} | |
for(int i = 0; i < N; i++) { | |
pthread_join(threads[i],NULL); | |
} | |
fprintf(stderr,"%d\n", COUNTER); | |
return EXIT_SUCCESS; | |
} |
@PariaHja: It should be 4000000 since the semaphore here acts as mutex where every of the 20 threads counts up the counter 200000 times.
I don't seem to get notifications for gists...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
now what should Counter be?200000 or 4000000(which is 20*200000)?