Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ pthread可以在构造函数中创建吗?_C++_Multithreading_Constructor_Pthreads_Threadpool - Fatal编程技术网

C++ pthread可以在构造函数中创建吗?

C++ pthread可以在构造函数中创建吗?,c++,multithreading,constructor,pthreads,threadpool,C++,Multithreading,Constructor,Pthreads,Threadpool,我想创建一个线程池。我有一个名为ServerThread.cpp的类,其构造函数应该执行以下操作: ServerThread::ServerThread() { for( int i=0 ; i<init_thr_num ; i++ ) { //create a pool of threads //suspend them, they will wake up when requests ar

我想创建一个线程池。我有一个名为ServerThread.cpp的类,其构造函数应该执行以下操作:

ServerThread::ServerThread()
   {
         for( int i=0 ; i<init_thr_num ; i++ )
         {
              //create a pool of threads
              //suspend them, they will wake up when requests arrive for them to process
         }
   }
ServerThread::ServerThread()
{

对于(int i=0;i),您可以在构造函数中这样做,但是应该知道Scott Meyers在他的有效的/更有效的C++书籍中清楚地解释的问题。 简言之,他的观点是,如果构造函数中出现任何类型的异常,则半备份对象不会被销毁。这会导致内存泄漏。因此Meyers的建议是使用“轻”构造函数,然后在对象完全创建后调用的
init
方法中执行“重”工作

此参数与在构造函数中创建pthread池没有严格的关系(因此,您可能会认为,如果只是创建pthread,然后立即挂起pthread,则不会引发异常),但它是关于如何在构造函数中执行的一般考虑(阅读:良好实践)

另一个需要注意的事项是构造函数没有返回值。虽然(如果没有引发异常)即使线程创建失败,也可以让对象保持一致状态,但最好是管理一种
init
start
方法的返回值


您也可以阅读有关该主题的内容,并且。

从严格的形式观点来看,构造函数实际上只是一个 像其他任何功能一样,应该没有任何问题。 实际上,可能存在一个问题:线程实际上可能会启动 在构造函数完成之前运行。如果线程需要 完全构造的
ServerThread
进行操作,然后您就进入了 问题当
ServerThread
是一个基本线程时,通常会出现这种情况 类,线程需要与派生类交互 是一个很难发现的问题,因为 使用线程调度算法后,新线程通常不会
立即开始执行。)

这与线程无关,Scott的建议已经被更高级的技术所取代:比如让基类或成员管理资源,这些资源在进入构造函数体之前就已经完全构造好了。(在本例中,线程池应该是一个成员,因此在出现异常时将调用其析构函数。)@James Kanze:在我的回答中,我已经指出了以下几点:“此参数与在构造函数中创建pthread池没有严格的关系”,而是与“良好实践”相关。此外,您在评论和自己的回答中都确认,建议使用一些特定的技术来正确处理此问题。
init
方法,无论是旧的还是简单的,都只是这些技术之一。无论如何,感谢您的评论。