C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 在循环迭代之间等待线程池中的线程大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些程序正在做一堆计算,而且由于我的新计算机有一个多核处理器,我决定重写我的多线程程序.我找到了Johan Hanssen Seferidis’ thpool library,我正在尝试使用它.

我有一个小循环(比如0

#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,请注明来意。