C 我可以让pthread\u t实例超出范围吗?

C 我可以让pthread\u t实例超出范围吗?,c,pthreads,C,Pthreads,我正在用C和pthreads编程。我有一个长时间运行的函数,我想在一个单独的线程中运行: void long_running_function(void * arg) { ... } void start_long_running_function(void * arg) { pthread_t thread; pthread_create( &thread , NULL , long_running_function , arg); /* What ab

我正在用C和pthreads编程。我有一个长时间运行的函数,我想在一个单独的线程中运行:

void long_running_function(void * arg) {  
  ...
}


void start_long_running_function(void * arg) {  
  pthread_t thread;  
  pthread_create( &thread , NULL , long_running_function , arg);
  /* What about the thread variable? */  
}  
当让start_long_运行_function()函数时,局部变量“thread”将超出范围。这可以吗?或者我可以冒问题的风险,例如,当长时间运行的函数()完成时

我已经尝试了代码中说明的方法,它似乎有效——但也许这只是运气

关于Joakim,是的——让变量超出范围是安全的。但请记住,在某个时刻,你必须做两件事中的一件:

1) pthread_detach()将其分离,这样内核将释放一些与之相关的内容

2) pthread_join()将其拆离,这会产生副作用


如果您不这样做,我认为这将是一个资源泄漏。

这是一个C结构,纯旧数据,因此当它超出范围时,没有析构函数引入副作用。失去范围的唯一含义是你再也看不到它了

我知道你的问题是C语言,但很多线程实现都是这样解决问题的:

class Thread {
    pthread_t handle;

    static void * start (void * self) {
        static_cast <Thread *> (self) -> run ();
    }

    protected: void run () = 0;

    public: void start () {
        pthread_create (&handle, NULL, start, this);
    }

    ~ Thread () {
        pthread_join (&handle, NULL);
    }
};
类线程{
pthread\u t句柄;
静态无效*开始(无效*自身){
静态_cast(self)->run();
}
受保护:无效运行()=0;
public:void start(){
pthread_创建(&handle,NULL,start,this);
}
~Thread(){
pthread_join(&handle,NULL);
}
};

您可以使用C做类似的事情,
arg
是指向
malloc
ed结构的指针,该结构包含线程句柄;线程函数
在终止时释放它。

好-谢谢。我将研究pthread_detach()-我想我可以将它添加到start_long_running_function()的末尾。@user422005:如果您知道您总是要分离它,那么您可以使用线程创建时的属性(pthread_attr_setdetachstate)首先在detached中创建线程。