c – 在循环迭代之间等待线程池中的线程
发布时间:2020-12-16 07:03:19 所属栏目:百科 来源:网络整理
导读:我有一些程序正在做一堆计算,而且由于我的新计算机有一个多核处理器,我决定重写我的多线程程序.我找到了Johan Hanssen Seferidis’ thpool library,我正在尝试使用它. 我有一个小循环(比如0 #include stdio.h#include "thpool.h"int i;void task1(int a){pri
我有一些程序正在做一堆计算,而且由于我的新计算机有一个多核处理器,我决定重写我的多线程程序.我找到了Johan Hanssen Seferidis’
thpool library,我正在尝试使用它.
我有一个小循环(比如0
#include <stdio.h> #include "thpool.h" int i; void task1(int a){ printf("# Thread working: %un",(int)pthread_self()); printf(" Task 1 running..n"); printf("%dn",10*i+a); } int main(){ int j; #define NUM_HANDLER_THREADS 3 thpool_t* threadpool; threadpool=thpool_init(NUM_HANDLER_THREADS); for (i=0; i<5; i++) for (j=0; j<10; j++) { thpool_add_work(threadpool,(void*)task1,(void*)j); }; sleep(2); puts("Will kill threadpool"); thpool_destroy(threadpool); return 0; } 编译: gcc main.c thpool.c -pthread -o test 执行上述操作应该(即我想要的)按顺序写入5个块0-9,10-19,…,40-49,但每个块的元素可以或多或少是随机顺序.相反,程序通过整个i循环过快,所以当线程开始写i == 5时,所以我以随机顺序得到50-59五次. 我希望我清楚自己要做什么.也许是这样的: for (i=0; i<5; i++) { for (j=0; j<10; j++) { thpool_add_work(threadpool,(void*)j); wait_for_all_threads_to_finish(); } }; 有任何想法吗?加入?退出?信号灯?这对我来说都是新手,所以谢谢你的耐心等待. 解决方法
我建议使用这样的信号量:
#include <stdio.h> #include <semaphore.h> #include "thpool.h" int i; sem_t sem; void task1(int a) { sem_post(&sem); printf("# Thread working: %un",(int)pthread_self()); printf(" Task 1 running..n"); printf("%dn",10*i+a); } int main(void) { int j; if (sem_init(&sem,0) == -1) abort(); #define NUM_HANDLER_THREADS 3 thpool_t* threadpool; threadpool=thpool_init(NUM_HANDLER_THREADS); for (i=0; i<5; i++) { for (j=0; j<10; j++) { thpool_add_work(threadpool,(void*)j); sem_wait(&sem); } } sleep(2); puts("Will kill threadpool"); thpool_destroy(threadpool); return 0; } 也尝试实验: void task1(int a) { printf("# Thread working: %un",10*i+a); sem_post(&sem); } 看看差异.祝好运. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |