在构造函数中创建线程 [英] Creating threads in Constructor

查看:123
本文介绍了在构造函数中创建线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在构造函数中创建线程是否安全.

所有线程都使用创建它们的对象的数据.
我在初始化所有成员变量后创建线程.

Is it safe to create threads in constructor.

All threads uses data of the object in which they are created.
I am creating threads after initializing all the member variables.

MyConstructor()
{

//////INITIALIZATION OF MEMBER VARIABLES START
.
.
.
.
.
.
.

//////INITIALIZATION OF MEMBER VARIABLES ENDS


CreateThread( NULL, 0, myThreadProc, this,0,NULL );


}

推荐答案

在C ++构造函数中使用虚函数是不安全的(永远不要尝试).如果您没有犯这个大错误,那为什么不呢?我只建议稍后而不是在构造函数中启动线程.这不是规则,只是更容易正确地设计代码.

—SA
It would be unsafe to use virtual functions in C++ constructor (never try it). If you don''t do this big mistake, why not? I would only recommend to start the thread later, not in constructor. This is not the rule, just easier to design your code properly.

—SA


这样做非常好...我不得不创建启动多个线程的管理器类,而构造函数正是在其中这样做最有意义.在很多情况下,如果您的线程无法启动,则无论如何都将结束应用程序.
I would say its perfectly fine to do so... I''ve had to create manager classes that start multiple threads and the constructor is where it makes most sense to do so. In a lot of cases, if your thread fails to start, you''re going to end the application anyway.


如果可以安全地处理(在对象逻辑中),可以这样做.可能是CreateThread失败.
You may do that if you can safely handle (in your object logic) possible CreateThread failures.


这篇关于在构造函数中创建线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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