~aritra1911/pthreads

0cc2f0036e8a9e7fd087fbb7febbdfe180331e94 — Aritra Sarkar 1 year, 11 months ago 7e8c51f
A Simple Condition Variable Example (cvsimple.c)
2 files changed, 73 insertions(+), 0 deletions(-)

M .gitignore
A cvsimple.c
M .gitignore => .gitignore +1 -0
@@ 12,3 12,4 @@ matrix_serial
matrix_peered
llist_demo
llist_threads_demo
cvsimple

A cvsimple.c => cvsimple.c +72 -0
@@ 0,0 1,72 @@
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

#define TCOUNT 10
#define WATCH_COUNT 12
#define INC_DELAY 1    /* useconds_t */

void *watch_count(void *arg);
void *inc_count(void *arg);

int count = 0;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t count_threshold_cv = PTHREAD_COND_INITIALIZER;

extern int
main(void)
{
    int i;
    int thread_ids[3] = { 0, 1, 2, };
    pthread_t threads[3];

    pthread_mutex_init(&count_mutex, NULL);
    pthread_cond_init(&count_threshold_cv, NULL);

    pthread_create(&threads[0], NULL, inc_count, (void *) &thread_ids[0]);
    pthread_create(&threads[1], NULL, inc_count, (void *) &thread_ids[1]);
    pthread_create(&threads[2], NULL, watch_count, (void *) &thread_ids[2]);

    for (i = 0; i < 3; i++) {
        pthread_join(threads[i], NULL);
    }
    return 0;
}

void *watch_count(void *arg)
{
    int idp = *(int *) arg;

    pthread_mutex_lock(&count_mutex);
    while (count < WATCH_COUNT) {

        /* 1. unlock(&count_mutex)
         * 2. wait_for_signal(&count_threshold_cv)
         * 3. lock(&count_mutex) */
        pthread_cond_wait(&count_threshold_cv, &count_mutex);

        printf("watch_count(): Thread %d, Count is %d\n", idp, count);
    }
    pthread_mutex_unlock(&count_mutex);

    return NULL;
}

void *inc_count(void *arg)
{
    int idp = *(int *) arg;

    int i;
    for (i = 0; i < TCOUNT; i++) {
        pthread_mutex_lock(&count_mutex);
        count++;
        printf("inc_count(): Thread %d, old count %d, new count %d\n",
                idp, count - 1, count);
        if (count == WATCH_COUNT)
            pthread_cond_signal(&count_threshold_cv);
        pthread_mutex_unlock(&count_mutex);
        usleep(INC_DELAY);
    }

    return NULL;
}