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

你可能感兴趣的:(thread,c++,开发语言)