C++ 11 std::async 使用问题

使用std::async遇到的异常问题

1.crash 在std中 thread 和 condition_variable相关的地方

2.导致线程卡住

vs2013下使用没问题,升级到vs2015后出现

 


#include "stdafx.h"

#include <stdarg.h>

#include <thread>

#include <future>

#include <iostream>

#include <windows.h>

using namespace std;

void connect()

{

	std::async(std::launch::async, [](){

		for (int i = 0; i < 5; ++i)

		{

		Sleep(1000);

			cout << i << endl;

		}

	});

	cout<< "finished connection" << endl;

}

int _tmain(int argc, _TCHAR* argv[])

{

	connect();

	while (1){

		cout << "main thread" << endl;

		Sleep(500);

	}

	cout << "end connection" << endl;

	return 0;

}

这样的写法在vs2013中没有问题,但在 vs2015中就引发以上两个问题,甚至间接的引发别的异常

在vs2015编译器下,包括在gcc编译器下,该异步方法会阻塞调用它的线程,直到子线程结束。而在vs2013的编译器下,异步方法不会阻塞当前线程.

std::future<T>::~future
 
C++
 
Thread support library
 
std::future
 
~future();

(since C++11) 



Releases any shared state. This means 
if the return object or provider holds the last reference to its shared state, the shared state is destroyed; and 
the return object or provider give
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,C++ 11 引入了 std::async 函数,可以用它来创建异步任务。std::async 函数的原型如下所示: ```c++ template <class Function, class... Args> std::future<typename std::result_of<Function(Args...)>::type> async(Function&& f, Args&&... args); ``` std::async 函数的作用是创建一个异步任务,并返回一个 std::future 对象,用于获取异步任务的返回值。std::async 函数的第一个参数是要执行的函数,后面的参数是该函数的参数。该函数会在一个新线程中执行,并在执行完成后返回结果。如果该函数抛出异常,则 std::future 对象中会保存该异常信息。 std::async 函数还可以指定执行策略,例如 std::launch::async 表示在新线程中执行异步任务,std::launch::deferred 表示在调用 std::future::get() 函数时执行异步任务。如果不指定执行策略,则由编译器自行决定。 以下是一个使用 std::async 函数创建异步任务的示例: ```c++ #include <iostream> #include <future> int foo(int x) { std::cout << "foo is running in thread " << std::this_thread::get_id() << std::endl; return x + 1; } int main() { std::future<int> result = std::async(std::launch::async, foo, 1); std::cout << "main is running in thread " << std::this_thread::get_id() << std::endl; std::cout << "result is " << result.get() << std::endl; return 0; } ``` 在上面的示例中,使用 std::async 函数创建了一个异步任务 foo,并将参数 1 传递给该函数。执行结果会保存在 std::future 对象中,可以使用 std::future::get() 函数获取异步任务的返回值。在主线程中也输出了一些信息,用于对比异步任务和主线程中的执行情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值