Skip to content

Instantly share code, notes, and snippets.

@sahib
Last active September 4, 2019 10:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sahib/1712515 to your computer and use it in GitHub Desktop.
Save sahib/1712515 to your computer and use it in GitHub Desktop.
A rather primitive Semaphore implementation in C using pthreads
#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
Copy link

PariaHja commented Jul 11, 2018

now what should Counter be?200000 or 4000000(which is 20*200000)?

@sahib
Copy link
Author

sahib commented Oct 29, 2018

@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