Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sitano
Created October 21, 2021 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sitano/5c5f387765a5ad5528b683753afa7581 to your computer and use it in GitHub Desktop.
Save sitano/5c5f387765a5ad5528b683753afa7581 to your computer and use it in GitHub Desktop.
experimenting with cond signal
#define _MULTI_THREADED
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* For safe condition variable usage, must use a boolean predicate and */
/* a mutex with the condition. */
int workToDo = 0;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#define NTHREADS 5
void check(const char *str, int err) {
if (err)
printf("[%d] err=%d: %s", gettid(), err, str);
}
void *threadfunc(void *parm) {
int rc;
while (1) {
check("lock()", pthread_mutex_lock(&mutex));
while (!workToDo) {
printf("[%d] %d: wait\n", gettid(), (int)parm);
rc = pthread_cond_wait(&cond, &mutex);
check("pthread_cond_wait()\n", rc);
}
printf("[%d] %d: wakeup\n", gettid(), (int)parm);
/* Under protection of the lock, complete or remove the work */
/* from whatever worker queue we have. Here it is simply a flag */
workToDo = 0;
check("unlock()", pthread_mutex_unlock(&mutex));
}
return NULL;
}
int main(int argc, char **argv) {
int rc=0;
int i;
pthread_t threadid[NTHREADS];
printf("Create %d threads\n", NTHREADS);
for(i=0; i<NTHREADS; ++i) {
rc = pthread_create(&threadid[i], NULL, threadfunc, (i+1));
check("pthread_create()", rc);
}
sleep(1); /* Sleep is not a very robust way to serialize threads */
while (1) {
check("lock()", pthread_mutex_lock(&mutex));
if (workToDo) {
printf("reacquired %d\n", workToDo);
}
workToDo++;
printf("\n");
printf("\n");
printf("\n");
printf("\n");
check("signal()", pthread_cond_signal(&cond));
check("unlock()", pthread_mutex_unlock(&mutex));
}
return 0;
}
@sitano
Copy link
Author

sitano commented Oct 21, 2021

output:

...
reacquired 4913




reacquired 4914




reacquired 4915
...

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