实现线程安全的成员函数的回调注册
#include <iostream>
#include <functional>
#include <memory>
#include <thread>
#include <chrono>
#include <atomic>
std::function<int(unsigned long, unsigned long, unsigned long, void*)> g_func;
std::thread th;
std::atomic_bool thrunning;
class MyClass {
public:
MyClass() { a = 10; };
~MyClass() {};
public:
int interruptFunc(unsigned long vi, unsigned long eventtype, unsigned long event, void* val) {
std::cout << "成员函数被调用!a = " << a << std::endl;
return 0;
}
private:
int a;
};
void testthread()
{
while (thrunning.load())
{
// 判断 g_func 是否可用
if (g_func) {
g_func(0, 10, 2, nullptr); // 调用传入的可调用对象
}
else {
std::cout << "g_func 未绑定有效的可调用对象!" << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
// 普通函数,接受 std::function 作为参数
int callMemberFunction(const std::function<int(unsigned long, unsigned long, unsigned long, void*)>& func) {
g_func = func;
thrunning.store(true);
th = std::thread(testthread);
return 0;
}
int main() {
// 创建 std::shared_ptr 管理对象生命周期
auto obj = std::make_shared<MyClass>();
// 使用弱引用智能指针std::weak_ptr 监视 shared_ptr
auto weakObj = std::weak_ptr<MyClass>(obj);
auto safeFunction1 = [weakObj](unsigned long vi, unsigned long eventtype, unsigned long event, void* val) -> int
{
if (auto sharedObj = weakObj.lock()) { // 检查对象是否仍然存在
sharedObj->interruptFunc(vi, eventtype, event, val);
}
else {
std::cout << "对象已经被销毁,无法调用函数\n";
}
return 0;
};
callMemberFunction(safeFunction1);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
obj.reset();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (th.joinable())
{
thrunning.store(false);
th.join();
}
return 0;
}