本文主要是介绍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
这篇关于C++ 将类的方法作为线程来运行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!