Skip to content

Instantly share code, notes, and snippets.

@bodokaiser
Created May 29, 2013 16:17
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 bodokaiser/5671561 to your computer and use it in GitHub Desktop.
Save bodokaiser/5671561 to your computer and use it in GitHub Desktop.
Incomplete example of using pthreads condition signaling.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_t threads[3];
pthread_cond_t cond_a;
pthread_cond_t cond_b;
pthread_mutex_t mutex;
int counter;
void * worker_one();
void * worker_two();
void * worker_three();
int main(int argv, const char ** argc) {
counter = 0;
pthread_cond_init(&cond_a, NULL);
pthread_cond_init(&cond_b, NULL);
pthread_mutex_init(&mutex, NULL);
pthread_create(&threads[0], NULL, worker_one, NULL);
pthread_create(&threads[1], NULL, worker_two, NULL);
pthread_create(&threads[2], NULL, worker_three, NULL);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_join(threads[2], NULL);
printf("Value started at %d and ends with %d.\n", 0, counter);
return 0;
}
void * worker_one() {
printf("Worker one started.\n");
pthread_mutex_lock(&mutex);
printf("Worker one starting work.\n");
while (counter < 10000) {
counter += 7;
}
pthread_cond_signal(&cond_a);
printf("Worker one finished work with: %d.\n", counter);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void * worker_two() {
printf("Worker two started.\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond_a, &mutex);
printf("Worker two starting work.\n");
while (counter > 1000)
counter -= 3;
printf("Worker two finished work with: %d.\n", counter);
pthread_cond_signal(&cond_b);
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_exit(NULL);
}
void * worker_three() {
printf("Worker three started.\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond_b, &mutex);
printf("Worker three starting work.\n");
counter /= 2;
printf("Worker three finished work with: %d.\n", counter);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment