更新时间:2023-11-09 23:34:34
您可能必须管理两个实例:
Foo
Foo
这将导致类 Bar
:
#include< iostream>
#include< thread>
struct Foo {
void print(std :: string s){//按值!
std :: cout<< s;
}
};
class Bar {
public:
void hello(){
//确保线程没有运行
//(只支持一个线程在这个例子中)
if(!foo_thread.joinable()){
//将新构造的线程移动到类成员。
foo_thread = std :: thread(
& Foo :: print,//指向Foo的成员函数的指针
& foo,//指向Foo实例的指针
hello\\\
// arguments by value
);
}
}
〜Bar(){
//确保线程已启动。
if(foo_thread.joinable()){
//这将阻塞,直到线程完成。
foo_thread.join();
}
}
private:
Foo foo;
std :: thread foo_thread;
};
int main()
{
Bar bar;
bar.hello();
}
注意:线程未分离。分离(不正确维护)正在运行的线程,将在程序结束时被杀死,并且该线程使用的资源(例如:文件句柄)可能不会返回到系统。
I need to start a thread that calls a public member function of the class Foo while inside of a public function that belongs to the class Bar. How do I achieve this?
I have tried the following (made trivial):
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;
}
This is my first time dealing with threading and the actual problem is a little more complex - BarFunc is a virtual function of a State class, with n-concrete classes implementing the different states my application can exist in, hence the question. I am not sure what to put as the last parameter, if anything. I have looked at this answer but cannot discern which syntax to use, if any of them even apply.
Finally, if this is bad practice all together, I would be grateful for any design advice.
You likely have to manage two instances:
Foo
Foo
That leads to the following sketch of a 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();
}
Note: The thread is not detached. A detached (not maintained properly) running thread, will get killed at end of the program and resources used by that thread (e.g.: file handles) might not be returned to the system.