pthread取消成功但在几百个线程后未能创建线程 [英] pthread cancel is successful but failing to create thread after few 100's of thread

查看:28
本文介绍了pthread取消成功但在几百个线程后未能创建线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里 pthread 在 1013 个线程之后没有被创建.我知道每个进程的线程创建都有限制,但在这里我取消了线程,并且在线程中我还调用了 pthread_testcancel() 来确定取消点.实际上这里发生了什么?有人可以帮我纠正线程创建失败吗?我是多线程的新手,如果您能向我提供详细的解释,那就太好了.谢谢你.

Here pthread is not getting created after 1013 threads. I know there is a limit in thread creation for every process, but here I am cancelling the thread and in thread I have also called pthread_testcancel() to make a cancellation point. Actually whats happening here? Can anybody help me correct the thread creation failure? I am new to multithreading and it would be great if you provide me with a detailed explanation. Thank you.

#include<iostream>
#include<pthread.h>


void* t(void*){ 
    while(1){
        pthread_testcancel();  //cancellation point?
    }
}
main(){
    pthread_t id;
    int i = 0;
    while(1){
        ++i;
        if(pthread_create(&id, 0, t, 0)){
            std::cout<<"\n failed to create "<<i;  //approx get hit at i=1013
            break;
        }
        if(pthread_cancel(id))  
            std::cout<<"\n i = "<<i;  //not at al executes, pthread_cancell is always successful?
    }
}

推荐答案

通过取消线程,您只是停止了线程 - 但系统仍在保留其资源.由于可用的线程资源数量有限,最终您将达到无法创建更多线程的限制.

By cancelling the thread, you are just stopping the thread - but the system is still keeping its resources around. Since there's only a limited amount of threading resources available, eventually you'll hit a limit where you can't create any more threads.

要清理线程资源,您需要:

To clean up the threads resources, you need to either:

  1. 在线程上执行 pthread_join()取消它,这将等待线程实际终止,并允许您取回返回值.
  2. 使用 pthread_detach() 分离线程创建或通过创建处于分离状态的线程).分离线程的资源会在线程结束时自动清理,但不允许您取回返回值.
  1. Do a pthread_join() on the thread after cancelling it, which will wait for the thread to actually terminate, and also allow you to get back a return value.
  2. Detach the thread either with pthread_detach() after creation or by creating the thread in a detached state). The resources of detached threads are automatically cleaned up when the thread ends, but it doesn't allow you to get back a return value.

这篇关于pthread取消成功但在几百个线程后未能创建线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆