赞
踩
自从c++11开始,使用std::thread类创建线程是非常方便的。
注意以下几点:
thread支持的对象参数类型如下:
在独立线程中执行函数:
#include <iostream> #include <thread> void foo(int a) { std::cout << a << '\n'; } int main() { // Create and execute the thread std::thread thread(foo, 10); // foo is the function to execute, 10 is the // argument to pass to it // Keep going; the thread is executed separately // Wait for the thread to finish; we stay here until it is done thread.join(); return 0; }
在独立线程上执行成员函数:
#include <iostream> #include <thread> class Bar { public: void foo(int a) { std::cout << a << '\n'; } }; int main() { Bar bar; // Create and execute the thread std::thread thread(&Bar::foo, &bar, 10); // Pass 10 to member function // The member function will be executed in a separate thread // Wait for the thread to finish, this is a blocking operation thread.join(); return 0; }
直接上代码:
#include <iostream> #include <thread> class Bar { public: void operator()(int a) { std::cout << a << '\n'; } }; int main() { Bar bar; // Create and execute the thread std::thread thread(bar, 10); // Pass 10 to functor object // The functor object will be executed in a separate thread // Wait for the thread to finish, this is a blocking operation thread.join(); return 0; }
代码如下:
#include <iostream> #include <thread> int main() { auto lambda = [](int a) { std::cout << a << '\n'; }; // Create and execute the thread std::thread thread(lambda, 10); // Pass 10 to the lambda expression // The lambda expression will be executed in a separate thread // Wait for the thread to finish, this is a blocking operation thread.join(); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。