gpt4 book ai didi

c - pthread C 中的池线程

转载 作者:太空宇宙 更新时间:2023-11-04 06:11:40 25 4
gpt4 key购买 nike

在我的 Advance OS 工作中,我需要从文件中读取数据并将其分配给线程以进行进一步处理。

这是我从文件中读取数据并将其传递给线程函数的代码

int main() {
FILE *fp = fopen(fileName, "r");
char str_pass[80][MAX_CHAR];

if (fp == NULL){
printf("Could not open file");
return 1;
}
int i=0;
pthread_t thread[THREADS];
int rc;

for(int th=1; th<=THREADS; th++)
{
if(fgets(str_pass[i], MAX_CHAR, fp) != NULL){
//printf("Hello, Thread %d\n",i);

rc = pthread_create(&thread[i], NULL, create_thread, (void*)str_pass[i]);
pthread_join(thread[i],NULL);

if(rc)
{
printf("ERROR; return code from pthread_create() is %d\n",rc);
exit(-1);
}
pthread_join(thread[i],NULL);
i++;
}
else{
printf("End of File");
exit(0);
}
}
pthread_exit(NULL);
fclose(fp);
return 0;
}

这是我的线程代码;

void * create_thread(void *hash_string)
{

gen_combinations(hash_string);

//sleep(1);
pthread_exit(NULL);
return NULL;
}

这段代码运行良好,它创建的线程与我在 THREADS 变量中定义的值一样多,除非它在文件中找不到任何记录。但现在我必须用线程池的概念来做。因为我无法生成与文件中的数据一样多的线程。

So I need to implement multi-threading using thread pooling. I did some search on it but didn't get any clearance on it. And now I'm totally stuck here and not getting any idea from where to start and how to do this work???

我们将不胜感激任何形式的帮助。

最佳答案

如果您还不熟悉“生产者/消费者问题”,请查阅“生产者/消费者问题”,特别是具有多个消费者的变体。您的主线程扮演生产者的角色,从输入文件中读取数据和参数,并将它们打包成整齐的工作单元——这些就是正在生产的小部件。工作线程扮演消费者的角色,接受工作单元并通过实际执行所描述的工作来“消费”它们。那是一个线程池。

您的特定实现可能不需要是通用的。它可以适本地设计和调整以专门解决手头的问题。

关于c - pthread C 中的池线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com