shared_futrue和futrue_status的用法
shared_futrue是一个类模板,类似于futrue,不同的是它的成员函数get()可以使用多次,因为是复制数据,而futrue的get()则是转移数据,使用一次之后,就失效了。
futrue_status是一个枚举类型,用来判断某个线程是否在规定时间执行完。
1 #include <iostream> 2 #include <future> 3 #include <Windows.h> 4 using namespace std; 5 6 int mythread() 7 { 8 cout << "my thread:" << std::this_thread::get_id() << " start" << endl; 9 cout << "waiting" << endl; 10 Sleep(5000); 11 cout << "my thread:" << std::this_thread::get_id() << " end" << endl; 12 return 2; 13 } 14 int main() 15 { 16 // future_status的用法 17 cout << "main thread:" << std::this_thread::get_id() << " start" << endl; 18 std::future<int> result = std::async(std::launch::async, mythread); 19 std::future_status status = result.wait_for(std::chrono::seconds(6)); //假设线程执行时间为6秒 20 if (status == std::future_status::timeout) 21 cout << "线程未执行完,超时了" << endl; 22 else if (status == std::future_status::ready) 23 cout << "线程成功执行" << endl; 24 else 25 cout << "线程被延迟执行" << endl; //仅当async的第一个参数为std::launch::async才有可能出现 26 27 // shared_future的用法,特点是它的成员函数get()是复制数据,所以get()可以使用多次 28 std::packaged_task<int(void)> pt(mythread); 29 thread t(std::ref(pt)); 30 t.join(); 31 std::shared_future<int> sf = pt.get_future(); 32 cout << sf.get() << endl; 33 cout << sf.get() << endl; 34 35 cout << "main thread:" << std::this_thread::get_id() << " end" << endl; 36 system("pause"); 37 return 0; 38 }
顺便简单介绍std:;atomic的用法,它是一个类模板,使用它称为原子操作,和互斥量作用一样,同样是保护操作数据,不同的是原子操作是针对一个变量,互斥量是针对一段代码。
使用方法:std::atomic<int> count = 0; //声明一个int类型的变量,在多个线程操作该数据时,相当于每个线程操作数据的时候会给count加锁,保证了其他线程不会干扰它,保护了数据。