我对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线程模型有什么好的例子吗?
最佳答案
在放置新作业的位置创建队列。创建5个线程。每个线程将选择一个作业并对其进行处理,然后选择下一个作业。一旦队列为空,线程就可以退出,可以完成线程连接。您需要对队列(或数组)进行同步。
关于c - 限制pthread中并发线程执行的数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6656383/