pthread_create()创建线程最大个数
線程應(yīng)用程序最常見導(dǎo)致創(chuàng)建線程失敗的原因是線程棧大小的設(shè)置。創(chuàng)建一個(gè)新的線程,默認(rèn)情況下系統(tǒng)為線程棧預(yù)留了2MB的尋址空間。線程棧起始于進(jìn)程虛擬 內(nèi)存的高端地址,并向虛擬內(nèi)存底端地址方向擴(kuò)展。取決于線程本身的大小以及其它線程內(nèi)存分配的情況,進(jìn)程虛擬地址空間消耗過快可能導(dǎo)致創(chuàng)建線程失敗。
這里有一個(gè)測(cè)試程序可以看到,Linux下最多可以創(chuàng)建多少個(gè)線程。
#include <pthread.h>
#include <stdio.h>
#include <string.h>
?
void *ThreadFunc()
{
????static int count = 1;
????printf ("Create thread%d/n", count);
????pthread_detach(pthread_self());
????count++;
???
}
?
main(void)
{
????int?????err;
????pthread_t tid;
????while (1){
???????????err= pthread_create(&tid, NULL, ThreadFunc, NULL);
???????????if(err != 0){
???????????????printf("can't create thread: %s/n",strerror(err));
???????????break;
???????????}??
????}
}
輸出結(jié)果如下:
Create thread 301
Create thread 302
can't create thread: Cannot allocate memory
用?ulimit -s?可以查看到棧的默認(rèn)大小為10240K
32位linux下的進(jìn)程用戶空間是3072M,?3072/10.24=300。為什么實(shí)際會(huì)比計(jì)算出來的多2個(gè),這個(gè)原因還不太清楚。(編者注:準(zhǔn)確算法是(3072*1024K)/10240K=307.2,實(shí)際會(huì)比計(jì)算出來的少5.2個(gè))
可以在調(diào)用pthread_create?的時(shí)候用?pthread_attr_getstacksize?設(shè)置棧的大小,或者直接用?ulimit -s?設(shè)置棧的大小。
如果修改上面的測(cè)試代碼為
#include <pthread.h>
#include <stdio.h>
#include <string.h>
?
void *ThreadFunc()
{
????static int count = 1;
????printf ("Create thread%d/n", count);
????pthread_detach(pthread_self());
????count++;
???
}
?
main(void)
{
????int?????err;
????pthread_t tid;
????while (1){
???????????err= pthread_create(&tid, NULL, ThreadFunc, NULL);
???????????if(err != 0){
???????????????printf("can'tcreate thread: %s/n", strerror(err));
???????????break;
???????????}??
????}
}
那么得到的結(jié)果將是:
Create thread 560000
Create thread 560001
……………
這里用到了pthread_detach(pthread_self())來釋放線程所占用的內(nèi)存資源(線程內(nèi)核對(duì)象和線程堆棧)。這樣就可以創(chuàng)建更多的線程,而不會(huì)出現(xiàn)Cannot allocate memory的錯(cuò)誤。
如果進(jìn)程中的某個(gè)線程執(zhí)行了pthread_detach(th),則th線程將處于DETACHED狀態(tài),這使得th線程在結(jié)束運(yùn)行時(shí)自行釋放所占用的內(nèi)存資源。一個(gè)可join的線程所占用的內(nèi)存僅當(dāng)有線程對(duì)其執(zhí)行了pthread_join()后才會(huì)釋放,因此為了避免內(nèi)存泄漏,所有線程的終止,要么已設(shè)為DETACHED,要么就需要使用pthread_join()來回收
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的pthread_create()创建线程最大个数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5、如何快速找到多个字典中的公共键(ke
- 下一篇: Ubuntu16.04安装配置Caffe