User Tools

Site Tools


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

c:thread-pool [2019-05-13 13:40]
ziggi created
c:thread-pool [2020-02-15 00:57]
Line 1: Line 1:
- 
-=====Pure C thread pool sample===== 
- 
-<code C thread-pool.c>​ 
-/* 
- * 
- * Copyright 2019 Oleg Borodin ​ <​borodin@unix7.org>​ 
- * 
- */ 
- 
-#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);​ 
-} 
-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; 
-} 
-</​code>​ 
- 
-===Out=== 
- 
-<​file>​ 
-$ "​./​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 
-</​file>​ 
- 
----- 
-[<>] 
-