c++ 高并发模板类std::async()

api列表

//c++11 chm手册 

///头文件
#include <future>

//模板定义
template< class Function, class... Args>
  async( Function&& f, Args&&... args );

template< class Function, class... Args >
  async( std::launch policy, Function&& f, Args&&... args );

//c++11起
enum class launch : /* unspecified */ {
 
     async =    /* unspecified */,
     deferred = /* unspecified */,
     /* implementation-defined */
};

实例

#include <iostream>
#include <future>
#include <unistd.h>

using namespace std;
void task() {
    for (int i = 0; i < 10; i++) {
        std::cout << "k" << endl;
    }
}

int main() {
    std::future<void> ret{ std::async(task) };
    for (int i = 0; i < 10; i++) {
        std::cout << "M";
    }
    ret.get();   //调用get方法后,会立即在此处阻塞main线程,直到task线程执行完毕
 	cout << "probe flag 1" << endl;
	sleep(10);
	
	// ret的生命周期为花括号之内,在退出花括号之前,一定会执行完毕task
	{
		std::future<void> ret{ std::async(std::launch::async,task) };
 	}
 	cout << "probe flag 2" << endl;
 	
	{
		std::future<void> ret{ std::async(std::launch::deferred ,task) };
		//ret.get();	//屏蔽此行,则task不会执行。去掉屏蔽,则阻塞main线程等待task执行完毕
 	}
 	cout << "probe flag 3" << endl; 	
 	
	pause();

    return 0;
}

说明:
std::async()会新创建一个线程去执行task,并将task执行结果返回std::future中,我们这里task返回void,所以没有捕获std::async()的返回值
std::launch::deferred参数,指定task线程不会阻塞当前线程
std::launch::async参数,指定task线程会阻塞当前线程

std::async()默认是属性值是std::launch::deferred

发布了61 篇原创文章 · 获赞 63 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/jacky128256/article/details/101372957
今日推荐