User Tools

Site Tools


Thread pool sample with runtime signal handler

thread-pool2.c
/*
 * Copyright 2004-2019 Oleg Borodin  <borodin@unix7.org>
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
 
int queue = 0;
pthread_mutex_t qmutex;
 
pthread_cond_t cond;
pthread_mutex_t mutex;
 
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;
}
 
void sighandler(int signo) {
    fprintf(stderr, "have signal, thread id %d, exit\n", (int)pthread_self());
    pthread_exit(NULL);
}
 
void* handler(void* ptr) {
    struct sigaction act;
    memset(&act, 0, sizeof(act));
 
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGRTMIN);
 
    act.sa_handler = sighandler;
    act.sa_mask = mask;
    sigaction(SIGRTMIN, &act, NULL);
 
    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();
    }
 
    pthread_kill(threads[0], SIGRTMIN);
    pthread_kill(threads[1], SIGRTMIN);
    pthread_kill(threads[2], SIGRTMIN);
 
    sleep(1);
 
    for (int i = 0; i < 12; i++) {
        qpush();
    }
 
    sleep(1);
    return 0;
}
$ "./pthread01"
thread create id = 16868608
thread create id = 16869888
thread create id = 16871168
thread create id = 16872448
thread create id = 16873728
have signal, thread id 16871168, exit
have signal, thread id 16868608, exit
have signal, thread id 16869888, exit
worker 16872448
worker 16872448
worker 16872448
worker 16872448
worker 16873728
worker 16873728
worker 16873728
worker 16873728
worker 16873728
worker 16873728
worker 16873728
worker 16872448

First PagePrevious PageBack to overviewNext PageLast Page