C++ 将类的方法作为线程来运行

C++ 将类的方法作为线程来运行
std::thread t(&Player::my_play, &a, 5);
t.join(); // 等待线程执行完毕

class Player {
   
public:
    Player(const std::string& name) : name_(name) {
   }

    void my_play(int times) {
   
        for (int i = 0; i < times; ++i) {
   
            std::cout << name_ << " is play times:" << (i+1) << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }

private:
    std::string name_;
};

int main() {
   
    std::cout << "start" << std::endl;
    // 创建Player对象a,传入名称"hello"
    Player a("hello");
    // a.my_play(3);
    
    // 创建线程,并指定类的方法作为线程函数
    std::thread t(&Player::my_play, &a, 5);
    // 等待线程执行完毕
    t.join();

    std::cout << "wait" << std::endl;
    // 等待所有任务完成
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "finish" << std::endl;

    return 0;
}

代码运行结果:

start
hello is play times:1
hello is play times:2
hello is play times:3
hello is play times:4
hello is play times:5
wait
finish

相关推荐

  1. C++ 方法作为线运行

    2024-01-29 08:10:04       34 阅读
  2. C++多线对于静态成员处理

    2024-01-29 08:10:04       12 阅读
  3. C# 线线使用方法、注意事项

    2024-01-29 08:10:04       36 阅读
  4. C++多线几种方法

    2024-01-29 08:10:04       7 阅读
  5. C++多线之通过成员函数作为线入口

    2024-01-29 08:10:04       33 阅读
  6. 线池相关学习

    2024-01-29 08:10:04       26 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-29 08:10:04       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-29 08:10:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-29 08:10:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-29 08:10:04       20 阅读

热门阅读

  1. scanf读取返回值问题

    2024-01-29 08:10:04       33 阅读
  2. 【数据分析】numpy基础第四天

    2024-01-29 08:10:04       33 阅读
  3. [lighttpd]lighttpd配置http强制跳转https

    2024-01-29 08:10:04       39 阅读
  4. 写一段防止sql注入的sql查询

    2024-01-29 08:10:04       31 阅读
  5. Zookeeper面试题合集

    2024-01-29 08:10:04       32 阅读
  6. VLM 系列——Qwen-VL 千问—— 论文解读

    2024-01-29 08:10:04       33 阅读
  7. c# Newtonsoft.Json 序列化和反序列化

    2024-01-29 08:10:04       35 阅读
  8. MySQL入门篇(2)-MySQL的安装和配置

    2024-01-29 08:10:04       28 阅读
  9. 浅析大数据汇总

    2024-01-29 08:10:04       31 阅读