在另一个 class 的成员函数中从成员函数启动线程
Starting a thread from a member function while inside another class's member function
我需要在属于 class Bar 的 public 函数内部启动一个调用 class Foo 的 public 成员函数的线程。我该如何实现?
我已经尝试了以下(变得微不足道):
void Bar::BarFunc()
{
// Do some BarFunc stuff
// Start a thread that needs to do stuff independently of BarFunc
std::thread t(&Foo::FooFunc, FooFunc params,..,.., ???);
t.detach();
return;
}
这是我第一次处理线程,实际问题有点复杂 - BarFunc 是一个 State class 的虚函数,n-concrete classes 实现了不同的声明我的应用程序可以存在于其中,因此出现了问题。如果有的话,我不确定将什么作为最后一个参数。我查看了 this 答案,但无法辨别使用哪种语法,如果它们中的任何一个适用的话。
最后,如果这一切都是不好的做法,我将不胜感激任何设计建议。
您可能需要管理两个实例:
Foo
的实例
- 线程执行
Foo
的成员函数
这导致以下 class Bar
的草图:
#include <iostream>
#include <thread>
struct Foo{
void print(std::string s) { // by value!
std::cout << s;
}
};
class Bar{
public:
void hello() {
// Ensure the thread is not running
// (Only one thread is supported in this example)
if( ! foo_thread.joinable()) {
// Move a newly constructed thread to the class member.
foo_thread = std::thread(
&Foo::print, // pointer to member function of Foo
&foo, // pointer to the instance of Foo
"hello\n" // arguments by value
);
}
}
~Bar() {
// Ensure the thread has been started.
if(foo_thread.joinable()) {
// This will block until the thread has finished.
foo_thread.join();
}
}
private:
Foo foo;
std::thread foo_thread;
};
int main()
{
Bar bar;
bar.hello();
}
注意:线程未分离。分离的(未正确维护)运行 线程将在程序结束时被杀死,该线程使用的资源(例如:文件句柄)可能不会返回到系统。
我需要在属于 class Bar 的 public 函数内部启动一个调用 class Foo 的 public 成员函数的线程。我该如何实现?
我已经尝试了以下(变得微不足道):
void Bar::BarFunc()
{
// Do some BarFunc stuff
// Start a thread that needs to do stuff independently of BarFunc
std::thread t(&Foo::FooFunc, FooFunc params,..,.., ???);
t.detach();
return;
}
这是我第一次处理线程,实际问题有点复杂 - BarFunc 是一个 State class 的虚函数,n-concrete classes 实现了不同的声明我的应用程序可以存在于其中,因此出现了问题。如果有的话,我不确定将什么作为最后一个参数。我查看了 this 答案,但无法辨别使用哪种语法,如果它们中的任何一个适用的话。
最后,如果这一切都是不好的做法,我将不胜感激任何设计建议。
您可能需要管理两个实例:
Foo
的实例
- 线程执行
Foo
的成员函数
这导致以下 class Bar
的草图:
#include <iostream>
#include <thread>
struct Foo{
void print(std::string s) { // by value!
std::cout << s;
}
};
class Bar{
public:
void hello() {
// Ensure the thread is not running
// (Only one thread is supported in this example)
if( ! foo_thread.joinable()) {
// Move a newly constructed thread to the class member.
foo_thread = std::thread(
&Foo::print, // pointer to member function of Foo
&foo, // pointer to the instance of Foo
"hello\n" // arguments by value
);
}
}
~Bar() {
// Ensure the thread has been started.
if(foo_thread.joinable()) {
// This will block until the thread has finished.
foo_thread.join();
}
}
private:
Foo foo;
std::thread foo_thread;
};
int main()
{
Bar bar;
bar.hello();
}
注意:线程未分离。分离的(未正确维护)运行 线程将在程序结束时被杀死,该线程使用的资源(例如:文件句柄)可能不会返回到系统。