gpt4 book ai didi

c - 达到计数 32751 后无法创建线程

转载 作者:行者123 更新时间:2023-11-30 19:04:56 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <pthread.h>
#include <errno.h>

void *my_thread(void *ddd)
{
printf("Thread created\n");
pthread_exit(NULL);
}

int main()
{
int ret = 0, counter = 0;
pthread_t et;
while(1)
{
ret = pthread_create(&et, NULL, my_thread, (void *)&counter);
if(ret)
{
printf("Ret = %d, errr = %d, couter = %d\n", ret, errno, counter);
break;
}
counter++;
}
return 0;
}

上面是我的C代码。检查了ulimit -s,它给出了8192。我没有使用pthred_join,因为我想并行处理我的数据,以及在完成其工作后如何退出线程。创建 32750 thred 后程序的输出是

Thread created 32750
Thread created 32751
Ret = 11, errr = 12, couter = 32751

最佳答案

来自pthread_create man page :

A thread may either be joinable or detached....

Only when a terminated joinable thread has been joined are the last of itsresources released back to the system....

When a detached thread terminates, its resources are automatically releasedback to the system:....

By default, a new thread is created in a joinable state, unless attr was setto create the thread in a detached state (using thread_attr_setdetachstate(3)).

这意味着对于您创建但未加入的任何线程,在其终止后仍会保留一些资源。在达到一定数量的线程后,您将耗尽资源。

为了避免这种情况,可以在创建线程后调用 pthread_detach 或在创建线程之前使用 pthread_attr_setdetachstate

关于c - 达到计数 32751 后无法创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870229/

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