[英]std::thread calling class methods
I have a small class:我有一个小class:
class MyData{
Struct1* pS;
public:
MyData() {
pS=new Struct1;
}
void saveData(Struct1* st) {
*pS = *st;
}
void printData() {
//print the struct
}
};
I want to modify the struct (call saveData) from a thread that needs to be running in the background, while the program may call printData sometime.我想从需要在后台运行的线程修改结构(调用 saveData),而程序有时可能会调用 printData。
I have this at the moment, but i don't know if it's thread safe.我现在有这个,但我不知道它是否是线程安全的。
void myFunction(MyData* data) {
while(1){
data->saveData(someStruct);
}
}
int main{
MyData *data = new MyData() ;
std::thread th_object(myFunction, data) ;
// more code
data->printData() ;
}
I also need a way to stop the thread when the programm reaches the end.我还需要一种方法来在程序结束时停止线程。
You should protect the members from data races with a mutex .您应该使用mutex保护成员免受数据竞争。 Example:例子:
#include <mutex>
#include <thread>
#include <atomic>
struct Struct1 {};
class MyData {
Struct1 pS;
std::mutex m_;
public:
void saveData(Struct1* st) {
std::unique_lock<std::mutex> lock(m_);
pS = *st;
}
void printData() {
std::unique_lock<std::mutex> lock(m_);
Struct1 copy = pS;
lock.unlock();
// print copy
}
};
void myFunction(MyData* data, std::atomic<bool>* stop) {
while(!*stop) {
Struct1 s;
data->saveData(&s);
}
}
int main() {
MyData data;
std::atomic<bool> stop{false};
std::thread th_object(myFunction, &data, &stop) ;
data.printData();
stop = true;
th_object.join();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.