如何让一个类作为可调用对象被thread调用?

news/2025/3/10 19:20:56/

如何让一个类作为可调用对象,被 std::thread 调用

在 C++ 中,可以让一个类对象作为可调用对象(Callable Object),然后用 std::thread 进行调用。要实现这一点,主要有三种方法:

  1. 重载 operator()(仿函数)
  2. 使用成员函数
  3. 使用 std::bindstd::function

1. 方法一:重载 operator()(仿函数)

最常见的方式是定义一个仿函数(functor),即重载 operator() 使类的实例可直接调用。

示例

#include <iostream>
#include <thread>class CallableObject {
public:void operator()() {  // 让对象像函数一样调用std::cout << "Thread running with CallableObject\n";}
};int main() {CallableObject obj;std::thread t(obj);  // 直接将对象传给 std::threadt.join();return 0;
}

解析

  • CallableObject 重载了 operator(),因此它的实例 obj 可以像函数一样被调用。
  • std::thread 可以直接接受 obj 作为参数,调用 operator()
  • 线程执行 obj.operator()(),输出:
    Thread running with CallableObject
    

2. 方法二:使用类的成员函数

可以直接用类的成员函数作为 std::thread 的目标,但要注意非静态成员函数需要绑定对象

示例

#include <iostream>
#include <thread>class Worker {
public:void run() {  // 成员函数std::cout << "Thread running with member function\n";}
};int main() {Worker worker;std::thread t(&Worker::run, &worker);  // 传递成员函数指针和对象t.join();return 0;
}

解析

  • &Worker::runWorker成员函数指针
  • &worker 传入对象指针,std::thread 需要对象来调用成员函数
  • 线程执行 worker.run(),输出:
    Thread running with member function
    

3. 方法三:使用 std::bind 绑定成员函数

如果 std::thread 需要额外的参数,可以用 std::bindstd::function 绑定成员函数和对象。

示例

#include <iostream>
#include <thread>
#include <functional>class Worker {
public:void run(int x) {std::cout << "Thread running with parameter: " << x << "\n";}
};int main() {Worker worker;std::thread t(std::bind(&Worker::run, &worker, 42));  // 绑定成员函数和参数t.join();return 0;
}

解析

  • std::bind(&Worker::run, &worker, 42) 绑定 worker.run(42)
  • std::thread 线程启动后会执行 worker.run(42)
  • 输出:
    Thread running with parameter: 42
    

4. 方法四:使用 std::function 结合 Lambda

另一种方式是用 std::function 存储可调用对象(比如 Lambda 或仿函数),然后传给 std::thread

示例

#include <iostream>
#include <thread>
#include <functional>class Worker {
public:void run(int x) {std::cout << "Thread running with parameter: " << x << "\n";}
};int main() {Worker worker;std::function<void()> func = std::bind(&Worker::run, &worker, 42);std::thread t(func);t.join();return 0;
}

解析

  • std::function<void()> 存储 worker.run(42)
  • std::thread 线程执行 func()
  • 输出:
    Thread running with parameter: 42
    

5. 选择哪种方式?

方法特点适用场景
仿函数(operator())直接使用对象,无需额外绑定线程对象无需额外参数
成员函数需要对象指针才能调用适用于普通类成员函数
std::bind 绑定成员函数允许传递额外参数需要动态传递参数时
std::function结合 std::bind,适用于通用接口适用于异步任务调度

对于简单任务,建议使用 重载 operator()。对于需要参数的任务,建议使用 std::bindstd::function


6. 组合使用:多个线程调用类对象

可以创建多个线程,并让它们执行类中的函数:

#include <iostream>
#include <thread>
#include <vector>class Worker {
public:void run(int id) {std::cout << "Thread " << id << " is running\n";}
};int main() {Worker worker;std::vector<std::thread> threads;for (int i = 0; i < 5; ++i) {threads.emplace_back(&Worker::run, &worker, i);}for (auto& t : threads) {t.join();}return 0;
}

输出

Thread 0 is running
Thread 1 is running
Thread 2 is running
Thread 3 is running
Thread 4 is running

总结

  • 让类成为可调用对象的常见方式:
    1. 仿函数(重载 operator()
    2. 成员函数(使用 &Class::method, &object 绑定)
    3. 使用 std::bind() 绑定成员函数
    4. 使用 std::function 存储可调用对象
  • 推荐用法
    • 简单的可调用对象仿函数
    • 普通成员函数std::thread t(&Class::method, &object)
    • 需要传参的成员函数std::bindstd::function
    • 多个线程调用同一个对象std::vector<std::thread>

多个线程调用同一个对象 ➝ std::vector<std::thread>

在 C++ 多线程编程中,我们经常希望多个线程同时调用同一个对象的成员函数。这通常用于:

  • 并行计算(多个线程操作同一个数据对象)
  • 任务调度(多个线程调用同一个处理对象)
  • 服务器/多客户端模型(多个线程访问同一个服务器对象)

使用 std::vector<std::thread> 可以创建多个线程,并让它们调用同一个对象的成员函数


1. 示例:多个线程调用同一个对象的成员函数

#include <iostream>
#include <thread>
#include <vector>class Worker {
public:void doWork(int id) {std::cout << "Thread " << id << " is working\n";}
};int main() {Worker worker;  // 所有线程共享这个对象std::vector<std::thread> threads;for (int i = 0; i < 5; ++i) {threads.emplace_back(&Worker::doWork, &worker, i);}for (auto& t : threads) {t.join();}return 0;
}

可能的输出(线程执行顺序可能不同):

Thread 0 is working
Thread 1 is working
Thread 2 is working
Thread 3 is working
Thread 4 is working

2. 代码解析

  1. 创建 Worker 对象

    Worker worker;
    
    • 这里 worker所有线程共享的对象
  2. 使用 std::vector<std::thread> 管理多个线程

    std::vector<std::thread> threads;
    
    • std::vector<std::thread> 存储多个 std::thread 对象,避免单独管理多个线程对象。
  3. 创建多个线程并调用 worker.doWork(i)

    for (int i = 0; i < 5; ++i) {threads.emplace_back(&Worker::doWork, &worker, i);
    }
    
    • &Worker::doWork:获取 Worker 类的成员函数指针。
    • &worker:传入对象指针,确保 doWorkworker 对象上调用。
    • i:传入线程的 ID,作为参数。
  4. 等待所有线程完成

    for (auto& t : threads) {t.join();
    }
    
    • 遍历 threads,对每个线程调用 join(),确保主线程等待所有子线程完成。

3. 线程安全问题

如果 Worker 类的 doWork 方法修改了成员变量,可能会发生数据竞争(Race Condition)。

示例:线程不安全

#include <iostream>
#include <thread>
#include <vector>class Worker {
private:int counter = 0;  // 共享变量public:void doWork(int id) {++counter;  // 线程不安全std::cout << "Thread " << id << " incremented counter to " << counter << "\n";}
};int main() {Worker worker;std::vector<std::thread> threads;for (int i = 0; i < 5; ++i) {threads.emplace_back(&Worker::doWork, &worker, i);}for (auto& t : threads) {t.join();}return 0;
}

可能的错误输出

Thread 0 incremented counter to 1
Thread 1 incremented counter to 2
Thread 2 incremented counter to 3
Thread 3 incremented counter to 2  // ❌ 竞争导致错误
Thread 4 incremented counter to 5

问题:

  • 多个线程同时修改 counter,导致数据竞争(Race Condition)。
  • 线程 3 可能在 counter = 2 之前读取旧值,导致计数错误。

4. 解决方案:使用 std::mutex 保护数据

使用 std::mutex 保护 counter,防止数据竞争。

#include <iostream>
#include <thread>
#include <vector>
#include <mutex>class Worker {
private:int counter = 0;std::mutex mtx;  // 互斥锁public:void doWork(int id) {std::lock_guard<std::mutex> lock(mtx);  // 加锁++counter;std::cout << "Thread " << id << " incremented counter to " << counter << "\n";}
};int main() {Worker worker;std::vector<std::thread> threads;for (int i = 0; i < 5; ++i) {threads.emplace_back(&Worker::doWork, &worker, i);}for (auto& t : threads) {t.join();}return 0;
}

输出

Thread 0 incremented counter to 1
Thread 1 incremented counter to 2
Thread 2 incremented counter to 3
Thread 3 incremented counter to 4
Thread 4 incremented counter to 5

修改点

  • 使用 std::mutex 互斥锁,防止多个线程同时访问 counter
  • std::lock_guard<std::mutex> 自动管理锁,避免手动 lock() / unlock()

5. 结论

  • 多个线程可以调用同一个对象的成员函数,可以使用 std::vector<std::thread> 统一管理线程。
  • 如果成员函数只读,不修改成员变量,线程是安全的。
  • 如果成员函数修改成员变量,必须使用 std::mutex 保护数据,防止数据竞争(Race Condition)。
  • std::vector<std::thread> 让多个线程的管理更加方便,避免单独管理多个 std::thread 变量。

这种模式在多线程服务器、任务分发、并行计算等场景非常常见。


http://www.ppmy.cn/news/1578162.html

相关文章

7. 机器人记录数据集(具身智能机器人套件)

1. 树莓派启动机器人 conda activate lerobotpython lerobot/scripts/control_robot.py \--robot.typelekiwi \--control.typeremote_robot2. huggingface平台配置 huggingface官网 注册登录申请token&#xff08;要有写权限&#xff09;安装客户端 # 安装 pip install -U …

【每日学点HarmonyOS Next知识】对话框回调问题、输入区域最大行数、web自定义节点、icon图标库、软键盘开关

1、HarmonyOS 使用promptAction.openCustomDialog(contentNode);无法触发onWillDismiss回调&#xff1f; 使用promptAction.openCustomDialog(contentNode);无法触发onWillDismiss回调 当用户执行点击遮障层关闭、左滑/右滑、三键back、键盘ESC关闭交互操作时&#xff0c;如果…

模型压缩技术(二),模型量化让模型“轻装上阵”

一、技术应用背景 在人工智能蓬勃发展的浪潮下&#xff0c;大模型在自然语言处理、计算机视觉等诸多领域大放异彩&#xff0c;像知名的GPT以及各类开源大语言模型&#xff0c;其规模与复杂度持续攀升。然而&#xff0c;这一发展也带来了挑战&#xff0c;模型越大&#xff0c;对…

大彩串口屏开发 —— MODBUS通信

目 录 Modbus通信方式 1 使用变量与协议设置方式 2 使用LUA脚本方式 3 两者结合 Modbus通信 大彩串口屏可以采用三种方式实现与其它设备进行modbus通信和逻辑处理。 方式 1 使用变量与协议设置 步骤1 在协议设置里进行设置&#xff0c;包括开启modbus协议&#xff0c;屏做为主…

Redis常问八股(一)

1.什么是缓存穿透&#xff1f;怎么解决&#xff1f; 答&#xff1a;缓存穿透是指查询一个一定不存在的数据&#xff0c;由于存储层查不到数据因此不写入缓存&#xff0c;这将导致这个不存在的数据每次请求都要到 DB 去查询&#xff0c;可能导致 DB 挂掉。这种情况大概率是遭到…

996引擎-问题处理:实现自定义道具变身卡

996引擎-问题处理:实现自定义道具变身卡 方案一、修改角色外观(武器、衣服、特效) 实现变身先看效果创建个NPC测试效果方案二、利用 Buff 实现变身创建:变身Buff配buff表,实现人物变形测试NPC创建道具:变身卡配item表,添加道具:变身卡触发函数参考资料方案一、修改角色外…

比特币中的相关技术

1.区块链&#xff1a;公共大账本 比特币的核心是一个叫区块链的技术。你可以把它想象成一个所有人都能看的“公共记账本”。比如你转钱给朋友&#xff0c;这笔交易就会被记在这个账本上&#xff0c;而且永久保存、无法篡改。 区块&#xff1a;账本每一页记录约10分钟的交易&am…

如何在WPS中接入DeepSeek并使用OfficeAI助手(超细!成功版本)

目录 第一步&#xff1a;下载并安装OfficeAI助手 第二步&#xff1a;申请API Key 第三步:两种方式导入WPS 第一种:本地大模型Ollama 第二种APIKey接入 第四步&#xff1a;探索OfficeAI的创作功能 工作进展汇报 PPT大纲设计 第五步&#xff1a;我的使用体验(体验建议) …