把类成员函数作为参数传递,并实现线程安全

实现线程安全的成员函数的回调注册

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值