大佬教程收集整理的这篇文章主要介绍了c – 在循环迭代之间等待线程池中的线程,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <stdio.h> #include "thpool.h" int i; void task1(int a){ printf("# Thread working: %u\n",(int)pthread_self()); printf(" Task 1 running..\n"); printf("%d\n",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: %u\n",(int)pthread_self()); printf(" Task 1 running..\n"); printf("%d\n",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: %u\n",10*i+a); sem_post(&sem); }
看看差异.祝好运.
以上是大佬教程为你收集整理的c – 在循环迭代之间等待线程池中的线程全部内容,希望文章能够帮你解决c – 在循环迭代之间等待线程池中的线程所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。