需要谨慎防止被保护的对象意外泄露到外界函数被更改状态。代码示例如下:
#include <functional>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
struct TData
{
public:
int n;
std::string str;
public:
TData()
{
n = 0;
str = "Moutain River";
}
};
class CDataWrapper
{
TData data;
std::mutex mt;
public:
void processData(std::function<void(const int& n, const std::string& str)> func)
{
mt.lock();
func(data.n, data.str);
mt.unlock();
}
};
void func(const int& n, const std::string& str)
{
std::cout << n << std::endl;
std::cout << str.c_str() << std::endl;
}
CDataWrapper* pdw = nullptr;
void task()
{
if (pdw != nullptr)
pdw->processData(func);
}
int main()
{
CDataWrapper dw;
pdw = &dw;
std::thread t(task);
t.join();
return 0;
}