User Tools

Site Tools


Pure C thread pool sample

thread-pool.c
/*
 *
 * Author, Copyright: Oleg Borodin <onborodin@gmail.com>
 *
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
 
int queue = 0;
pthread_mutex_t qmutex;
void qpush() {
    pthread_mutex_lock(&qmutex);
    queue++;
    pthread_mutex_unlock(&qmutex);
    pthread_cond_signal(&cond);
}
void qpop() {
    pthread_mutex_lock(&qmutex);
    queue--;
    pthread_mutex_unlock(&qmutex);
}
int qsize() {
    pthread_mutex_lock(&qmutex);
    int tmp = queue;
    pthread_mutex_unlock(&qmutex);
    return tmp;
}
 
pthread_cond_t cond;
pthread_mutex_t mutex;
 
void* handler(void* ptr) {
    while (1) {
        while(qsize() == 0) {
            pthread_cond_wait(&cond, &mutex);
        }
        if (qsize() > 0) qpop();
        //pthread_mutex_unlock(&mutex);
        printf("worker %d\n", (int)pthread_self());
    }
    return NULL;
}
 
int main(int argc, char **argv) {
    const int poolsize = 5;
    pthread_t threads[poolsize];
    for (int i = 0; i < poolsize; i++) {
        pthread_create(&threads[i], NULL, handler, NULL);
    }
    for (int i = 0; i < poolsize; i++) {
        pthread_detach(threads[i]);
        printf("thread create id = %d\n", (int)threads[i]);
    }
 
    for (int i = 0; i < 12; i++) {
        qpush();
    }
 
    sleep(1);
    return 0;
}

Out

$ "./pthread01"
thread create id = 16868608
thread create id = 16869888
thread create id = 16871168
thread create id = 16872448
thread create id = 16873728
worker 16868608
worker 16871168
worker 16871168
worker 16871168
worker 16873728
worker 16868608
worker 16868608
worker 16868608
worker 16871168
worker 16872448
worker 16869888
worker 16873728

[<>]