http://www.cnblogs.com/zhuyp1015/archive/2012/04/08/2438288.html
C++11提供了新头文件<thread>、<mutex>、<atomic>、<future>等用于支持多线程。
基本形式
#include <thread> #include <iostream> void hello() { std::cout << "Hello from thread " << std::endl; } int main() { std::thread t1(hello); t1.join();//join()方法阻塞主线程 std::cout << "Main Thread" << std::endl; return 0; }
支持stl和lambda
#include <thread> #include <iostream> #include <vector> int main() { std::vector<std::thread> threads; for (int i = 0; i < 5; ++i){ threads.push_back(std::thread([](){ std::cout << "Hello from lamda thread " << std::this_thread::get_id() << std::endl; })); } for (auto& thread : threads){ thread.join(); } std::cout << "Main Thread" << " " << std::this_thread::get_id() << std::endl; return 0; }
可以通过sleep_for来使线程睡眠一定的时间:
#include <thread> #include <iostream> #include <mutex> using namespace std; int main() { std::mutex m; thread t1([&m]() { std::this_thread::sleep_for(chrono::seconds(10)); for (int i = 0; i<2; i++) { m.lock(); cout << "In t1 ThreadID : " << std::this_thread::get_id() << ":" << i << endl; m.unlock(); } }); thread t2([&m]() { std::this_thread::sleep_for(chrono::seconds(1)); for (int i = 0; i<2; i++) { m.lock(); cout << "In t2 ThreadID : " << std::this_thread::get_id() << ":" << i << endl; m.unlock(); } }); t1.join(); t2.join(); cout << "Main Thread" << endl; return 0; }
延时有这几种类型:nanoseconds、microseconds、milliseconds、seconds、minutes、hours。
#include <thread> #include <iostream> #include <vector> #include <mutex> struct Counter { std::mutex mutex; int value; Counter() : value(0) {} void increment(){ mutex.lock(); ++value; mutex.unlock(); } void decrement(){ mutex.lock(); --value; mutex.unlock(); } }; int main(){ Counter counter; std::vector<std::thread> threads; for (int i = 0; i < 5; ++i){ threads.push_back(std::thread([&](){ for (int i = 0; i < 10000; ++i){ counter.increment(); } })); } for (auto& thread : threads){ thread.join(); } std::cout << counter.value << std::endl; return 0; }