在不超出范围的情况下将指针传递到线程
Passing pointers to threads without being out of scope
我得到了一个预定义的类/函数的预定义.lib文件。
我需要创建一个:
Cdefined *p = new Cdefined;
p->Init();
在 main() 程序中,在调用我的线程之前初始化我的类对象。
但是,我意识到在我的每个线程中,我都必须调用:
p->doProcess();
为每个线程运行一段代码。
但是,除非我调用p->Init()
,否则此功能将不起作用。
既然现在我至少有 2 个 p 作用域(一个在 main()
中创建,其中 N 个在 N 个线程中创建),我该如何设计我的线程,以便可以在没有作用域错误的情况下传入类?[我的限制是p->Init()
必须被召唤main()
]
如果对象的生存期只是绑定到 main
的范围,那么这很容易 - 只需确保在销毁对象之前已停止并连接所有线程即可。这可以通过使用范围在 main
范围内的智能指针管理对象来更好地实施,或者更简单地说,通过在 main
内为对象提供自动生存期:
void thread_func(Cdefine *);
int main()
{
Cdefine thing;
thing.Init();
std::thread thread1(thread_func, &thing);
std::thread thread2(thread_func, &thing);
// do stuff
thread1.join();
thread2.join();
// Now it's safe to destroy the object
}
在更复杂的情况下,您不能简单地将对象绑定到比线程更广泛的范围,您可以考虑使用 std::shared_ptr
来管理它(如果您坚持使用 2011 年之前的语言,则可以使用 std::tr1::shared_ptr
或boost::shared_ptr
)。例如:
void thread_func(std::shared_ptr<Cdefine> p);
void spawn_threads()
{
std::shared_ptr<Cdefine> p = std::make_shared<Cdefine>();
p->Init();
std::thread thread1(thread_func, p);
std::thread thread2(thread_func, p);
thread1.detach();
thread2.detach();
// The threads can carry on doing their thing, and it's safe to
// drop our shared pointer. The object will be deleted when the
// last thread drops its pointer to it.
}
顺便说一句,为什么在构造对象后需要调用Init
函数?为什么不在构造函数中初始化它,因为这就是构造函数的用途?
为每个
线程创建一个Cdefined
实例,调用其Init
方法,并将其作为参数传递给线程。
像这样:
for (int i = 0; i < NUM_THREADS; i++)
{
Cdefined *p = new Cdefined;
p->Init();
create_thread(thread_func, p);
}
和线程功能:
void *thread_func(void *data)
{
Cdefine *p = reinterpret_cast<Cdefine*>(data);
for (;;)
{
// Do stuff...
p->doProcess();
// Do other stuff
}
return 0;
}
相关文章:
- 如何检索指向在单独线程上运行的函数的移动指针?
- 如何将'this'指针传递给C++ WinAPI 线程?
- 从子线程访问指针
- 将字符串指针传递到C++和Xcode 11.1中不同线程上运行的函数
- 通过std::shared_ptr使用Rcpp和RcppParallel的线程安全函数指针
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- 线程中的成员函数指针
- 如何安全地终止线程?(使用指针)C++
- 指向成员对象的指针 - 中断线程
- 是否可以访问非线程安全容器内指针指向的值(线程安全映射中的条目)?
- 如何抓取指向Qt中弹出对话框的指针,该对话框阻止了QTest中的UI线程
- 将指针传递到另一个线程的正确方法
- CPP:如何使用需要指针的方法创建线程
- 启动线程会导致指针初始化时出现分段错误
- 是否访问指针元组和互斥锁线程安全
- 在容器中存储指向对象的指针时的线程安全
- 为什么当我在构造函数中创建线程时,实例化对象和对象的指针的行为不同
- 指针在不同的线程中获得错误的价值
- C++ 线程函数指针实现返回错误无效使用非静态成员函数
- 指向对象初始化的静态指针——线程安全