gpt4 book ai didi

c - pthreads : allowed number of threads

转载 作者:行者123 更新时间:2023-12-04 10:43:15 25 4
gpt4 key购买 nike

我现在已经在一个使用 pthreads 的小 C 程序上工作了几天。我昨天或多或少花了一整天时间寻找死锁错误,但现在我发现问题并不是真正的死锁错误。下面的一段代码有完全相同的问题。

#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#define NTHREADS 507

pthread_mutex_t runningThreadsMutex;
pthread_cond_t runningThreadsCond;
int runningThreads = 0;

void* HelloWorld(void* arg) {
sleep(1);

pthread_mutex_lock(&runningThreadsMutex);
runningThreads--;
printf("End thread %d\n", runningThreads);
pthread_cond_signal(&runningThreadsCond);
pthread_mutex_unlock(&runningThreadsMutex);

return NULL;
}

int main() {
pthread_t thread;

pthread_mutex_init(&runningThreadsMutex, NULL);
pthread_cond_init(&runningThreadsCond, NULL);

for (int i = 0; i < NTHREADS; ++i) {
pthread_mutex_lock(&runningThreadsMutex);
printf("Create thread %d\n", runningThreads++);
pthread_mutex_unlock(&runningThreadsMutex);
pthread_create(&thread, NULL, HelloWorld, NULL);
// pthread_detach(thread);
}

pthread_mutex_lock(&runningThreadsMutex);
while(runningThreads > 0) {
pthread_cond_wait(&runningThreadsCond, &runningThreadsMutex);
}
pthread_mutex_unlock(&runningThreadsMutex);
return 0;
}

对于 NTHREADS < 506,上面的代码似乎在我的笔记本电脑(64 位 linux 机器)上运行良好。在那种情况下,它打印出如下内容:

Create thread 0
Create thread 1
.
.
.
Create thread 505
End thread 505
End thread 504
.
.
.
End thread 0

并按预期终止。但是,如果我使用 NTHREADS >= 506,例如NTHREADS = 510 我得到

Create thread 0
Create thread 1
.
.
.
Create thread 509
End thread 509
End thread 508
.
.
.
End thread 4

它停止而不会终止的地方。所以看起来最后四个 (510-506=4) 线程永远不会终止(或者根本不会开始?)。

我也在旧的 32 位 Linux 机器上尝试了这段代码。在那里我得到了相同的行为,除了它适用于 NTHREADS < 382 但不适用于 NTHREADS >= 382(而不是 506)。

当我用谷歌搜索解决方案时,我还发现了这个问题:http://bytes.com/topic/c/answers/728087-pthreads-limit ,有人在使用 pthread_join 时遇到同样的问题(这在使用 pthreads 时可能更自然)但他们没有给出任何好的解释。

任何人都可以向我解释我做错了什么以及这段代码的根本问题是什么?我想这一定是对允许线程数的某种限制,但我应该如何处理它?<​​/p>

最佳答案

您需要检查 pthread_create 的返回值。如果它非零,则该函数无法创建线程。一个典型的问题是新线程的堆栈内存不足。例如对于每个线程 1Mb 的堆栈,系统将需要至少 510Mb 的可用内存来启动 510 个线程。

为什么要运行这么多线程?除非你有一个拥有数百个处理器的大规模并行系统,否则这些线程只会竞争 CPU 时间和其他资源。以最合适的顺序执行工作的线程数量较少(与系统中的处理器数量数量级相同)可能会更好。

关于c - pthreads : allowed number of threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3387762/

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