【问题标题】:Limiting number of concurrent theads execution in pthreads限制 pthread 中并发执行的线程数
【发布时间】:2011-07-11 20:49:44
【问题描述】:

我对 pthread 世界很陌生。 我需要处理一个带有命令列表的文件,假设文件看起来像这样 -

Command1
Command2
Command3
.
.
CommandN

对于每个命令,我想创建一个线程。现在的问题是,如果有大量命令,我最终会创建大量线程,这是我想要避免的。所以,我想限制在任何给定时间点执行的线程数。假设这个数字是 5。

有人可以建议如何实现这一目标吗?我正在使用以下code 进行学习-

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4

void *BusyWork(void *t)
{
   int i;
   long tid;
   double result=0.0;
   tid = (long)t;
   printf("Thread %ld starting...\n",tid);
   for (i=0; i<1000000; i++)
   {
      result = result + sin(i) * tan(i);
   }
   printf("Thread %ld done. Result = %e\n",tid, result);
   pthread_exit((void*) t);
}

int main (int argc, char *argv[])
{
   pthread_t thread[NUM_THREADS];
   pthread_attr_t attr;
   int rc;
   long t;
   void *status;

   /* Initialize and set thread detached attribute */
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   for(t=0; t<NUM_THREADS; t++) {
      printf("Main: creating thread %ld\n", t);
      rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t); 
      if (rc) {
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
         }
      }

   /* Free attribute and wait for the other threads */
   pthread_attr_destroy(&attr);
   for(t=0; t<NUM_THREADS; t++) {
      rc = pthread_join(thread[t], &status);
      if (rc) {
         printf("ERROR; return code from pthread_join() is %d\n", rc);
         exit(-1);
         }
      printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status);
      }

printf("Main: program completed. Exiting.\n");
pthread_exit(NULL);
}

对于 Boss/Worker 线程模型有什么好的例子吗?

【问题讨论】:

    标签: c multithreading pthreads


    【解决方案1】:

    创建一个放置新作业的队列。创建 5 个线程。每个线程将选择一个工作并处理它,然后它将选择下一个工作。一旦队列为空,线程可以退出,您可以执行 thread_join。您需要对队列(或数组)进行同步。

    【讨论】:

    • 谢谢!你能帮我理解为什么需要同步吗?如果我将 5 个元素加入队列,然后创建 5 个线程,每个线程将处理分配给它的一个元素,然后将该元素出队,为什么需要同步?
    • 出队操作不是原子的。两个线程可以同时获取下一个作业,这会导致问题。查看 pthread_mutex_t 和 pthread_cond_t 的教程。
    【解决方案2】:

    main 中初始化一个初始值为4 的信号量。在BusyWork 函数中,每个线程应在进入时等待信号量,然后在退出时发布。加入所有线程后,销毁信号量。

    编辑!忘了link

    【讨论】:

      【解决方案3】:

      您正在寻找的似乎是线程池的概念。 Wikipedia Page 有一些不错的链接到实现这一点的文章。另外,在 github 上搜索“线程池”应该会给你一些不错的简单实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多