标签: stdasync

std :: async中的超时

有没有办法在std :: async方法中实现超时,所以如果线程没有在指定的时间内完成,我希望这个调用超时并完成.我该如何实现此功能.

c++ std c++11 stdasync stdthread

4
推荐指数
2
解决办法
4462
查看次数

"没有匹配函数来调用'async(std :: launch,<unresolved overloaded function type>,std :: string&)'"

我正在尝试创建一个线程使用std::async,但我不断收到错误"没有匹配函数来调用' async(std::launch, <unresolved overloaded function type>, std::string&)''就行了

ConnectFuture = std::async(std::launch::async, Connect_T,ip);
Run Code Online (Sandbox Code Playgroud)

以下是产生此行为的代码:

#include <future>

class libWrapper
{
public:

    void Connect(std::string ip);
    void Connect_T(std::string ip);

private:

    std::future<void> ConnectFuture;
};



void libWrapper::Connect(std::string ip){

    auto status = ConnectFuture.wait_for(std::chrono::seconds(0));
    if (status != std::future_status::timeout)
    {
        ConnectFuture = std::async(std::launch::async, Connect_T,ip);

    }
}

void libWrapper::Connect_T(std::string ip)
{


}

int main(int argc, char** argv) {
    libWrapper lW;
    lW.Connect("192.168.3.1");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ c++11 stdasync

4
推荐指数
1
解决办法
5809
查看次数

VS2015 std :: async很奇怪

在VS2015的下面的代码中,我进入acefbd了第一行,这是正确的.但在第二次测试中,我分成单独的行,输出是abcdef.

这是预期的行为吗?

#include <future>
#include <iostream>

using namespace std;

void a () {
std::cout << "a";
std::this_thread::sleep_for (std::chrono::seconds (3));
std::cout << "b";
}

void c () {
std::cout << "c";
std::this_thread::sleep_for (std::chrono::seconds (4));
std::cout << "d";
}

void e () {
std::cout << "e";
std::this_thread::sleep_for (std::chrono::seconds (2));
std::cout << "f";
}

int main () 
{
    std::async (std::launch::async, a), std::async (std::launch::async, c),  std::async (std::launch::async, e);

cout << "\n2nd Test" << endl;

std::async (std::launch::async, a);
std::async (std::launch::async, c); …
Run Code Online (Sandbox Code Playgroud)

c++ stdasync visual-studio-2015

3
推荐指数
1
解决办法
120
查看次数

您是否需要存储 std::async 的 std::future 返回值?

考虑以下代码:

#include <iostream>
#include <future>
#include <thread>
#include <chrono>

void func()
{
    std::async(std::launch::async, []{std::this_thread::sleep_for(std::chrono::milliseconds(1000)); });
}

int main()
{

    std::cout << "start " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() << "ms\n";
    func();
    std::cout << "stop  " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() << "ms\n";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

start 18737230ms
stop  18738230ms
Run Code Online (Sandbox Code Playgroud)

我们可以看到1秒过去了才func()返回。然而,没有存储 std::future std::async(...);- 即:auto f = std::async(...)

这似乎有效 - 但我想知道它的工作机制是什么。如果我有一个 std::future (在我的小例子中是 auto f ),那么当它超出范围时,它会整理线程 - 即等待 1 秒,然后线程在幕后被处理。

进一步测试:

start 18737230ms
stop  18738230ms
Run Code Online (Sandbox Code Playgroud)

给出:

start 4448133ms
stop1 4449133ms - 1 sec …
Run Code Online (Sandbox Code Playgroud)

c++ c++11 stdasync

3
推荐指数
1
解决办法
1127
查看次数

如果父/主线程死亡,std :: async调用会发生什么

如果我是对的,std :: async使用一个新线程并调用其中的方法.我想知道如果主线程或父线程死亡会发生什么.控制异步方法的线程是否也会死亡.

c++ std c++11 stdasync stdthread

2
推荐指数
1
解决办法
533
查看次数

使用std :: async的奇怪行为

请考虑以下示例代码:

#include <future>
#include <array>
#include <cassert>

typedef std::array<int, 5> foo_t;

foo_t* bar(foo_t& foo) {
   return &foo;
}

int main() {
   foo_t foo;
   auto a = std::async(bar, foo);
   auto b = std::async(bar, foo);
   assert(a.get() == b.get());
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

GCC 4.6.3编译时没有任何投诉.但是,这在运行时失败:

test: test.cpp:15: int main(): Assertion `a.get() == b.get()' failed.
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

但是,GCC 4.8.2拒绝编译该文件:

In file included from /usr/local/include/c++/4.8.2/future:38:0,
                 from test.cpp:1:
/usr/local/include/c++/4.8.2/functional: In instantiation of 'struct std::_Bind_simple<std::array<int, 5ul>* (*(std::array<int, 5ul>))(std::array<int, 5ul>&)>':
/usr/local/include/c++/4.8.2/future:1525:70:   required from 'std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, …
Run Code Online (Sandbox Code Playgroud)

c++ gcc c++11 stdasync

2
推荐指数
1
解决办法
852
查看次数

异步函数产生不一致的结果

我有一个异步运行的函数.不幸的是,它只会偶尔吐出正确的答案.futures[i].get()每次运行代码时由更改表示的值.我是多线程的新手.

double async_func() const {

    vector<future<double>> futures;

    double val = 0;
    for (int i = 0; i < rows; i++) {
        futures.push_back(std::async(std::launch::async, [&] {return minor(i,0).determinant();}) );
    }       
    for (int i = 0; i < rows; i++) 
        val += futures[i].get();

    return val;
}
Run Code Online (Sandbox Code Playgroud)

c++ multithreading future c++11 stdasync

2
推荐指数
1
解决办法
85
查看次数

std :: async,std :: function对象和带有'callable'参数的模板

#include <functional>
#include <future>

void z(int&&){}
void f1(int){}
void f2(int, double){}

template<typename Callable>
void g(Callable&& fn)
{
    fn(123);
}

template<typename Callable>
std::future<void> async_g(Callable&& fn)
{
    return std::async(std::launch::async, std::bind(&g<Callable>, fn));
}

int main()
{
    int a = 1; z(std::move(a)); // Does not work without std::move, OK.

    std::function<void(int)> bound_f1 = f1;
    auto fut = async_g(bound_f1); // (*) Works without std::move, how so?
    // Do I have to ensure bound_f1 lives until thread created by async_g() terminates?
    fut.get();

    std::function<void(int)> bound_f2 = std::bind(f2, std::placeholders::_1, …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11 stdasync

1
推荐指数
1
解决办法
561
查看次数

C++ std :: async不会产生新线程

C++ 11

int main(int argc, char** argv) {
    std::async(std::launch::async, [](){ 
        while(true) cout << "async thread" <<endl; 
    });
    while(true) cout << "main thread" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我期望输出应该是交错的async thread, main thread因为应该有2个不同的线程.

但事实并非如此.

它输出:

async thread
async thread
async thread
async thread
...
Run Code Online (Sandbox Code Playgroud)

我想只有一个主题.有人能告诉我为什么它不会产生新的线程std::async吗?谢谢.

c++ multithreading asynchronous stdasync

1
推荐指数
1
解决办法
1003
查看次数

超出范围时,从std :: async返回的std :: future挂起

我使用的组合std::asyncstd::futureC++ 11.我正在使用对我在代码中执行的某项活动强制执行time_out,这可能需要一些时间,因为我尝试连接到服务器.

以下是代码:

#include <future>
#include <chrono>

std::size_t PotentiallyLongRunningActivity() {
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(10000s);
    return 10;
}

bool DoActivity() {

  bool activity_done = false;
  auto my_future_result(std::async(std::launch::async, []() {
      return PotentiallyLongRunningActivity(); //returns size_t
  }));

  std::future_status my_future_status = my_future_result.wait_for(std::chrono::milliseconds(800));
  if (my_future_status == std::future_status::timeout) {
      activity_done = false;
  }
  else if (my_future_status == std::future_status::ready) {
      if (my_future_result.valid() && my_future_result.get() > 0) {
          activity_done = true;
      }
  }

  return activity_done;
  //my_future_result hangs while exiting this method …
Run Code Online (Sandbox Code Playgroud)

c++ c++11 stdasync std-future

1
推荐指数
1
解决办法
4387
查看次数

C++ 在向量中存储 std::future 形式的 std::async 并等待所有人

我想与 std::async 并行执行多项任务,然后等到所有期货都完成。

void update() {
  // some code here
}

int main() {

  std::vector<std::future<void>> handles(5);

  for (int i = 0; i < 5; ++i) {
    auto handle = std::async(std::launch::async, &update);
    handles.emplace_back(std::move(handle));
  }

  for (auto& handle : handles) {
    handle.wait();
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是在执行程序时,我得到了一个std::future_error抛出:

terminate called after throwing an instance of 'std::future_error'
  what():  std::future_error: No associated state
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

我想知道为什么。我不应该能够存储未来的对象吗?

c++ stdasync std-future

1
推荐指数
1
解决办法
74
查看次数

如何将变量传递给std :: async?

我怎样才能将向量传递给异步调用?

std::vector<int> vectorofInts;
vectorofInts.push_back(1);
vectorofInts.push_back(2);
vectorofInts.push_back(3);

std::async([=]
{
    //I want to access the vector in here, how do I pass it in
    std::vector<int>::iterator position = std::find(vectorofInts.begin(), vectorofInts.end(), 2);
    //Do something 
}
Run Code Online (Sandbox Code Playgroud)

c++ c++11 stdasync

0
推荐指数
1
解决办法
489
查看次数

在抽象基类中使用c ++ 11的std :: async

为什么不在这个抽象基类中创建这样的线程呢?我试图抽象出从这个基类派生的用户的所有多线程细节.当我清楚地写出callbackSquare返回类型时,我不明白它为什么说"没有类型命名为'type'" int.

#include <iostream>
#include <future>
#include <vector>

class ABC{
public:
    std::vector<std::future<int> > m_results;
    ABC(){};
    ~ABC(){};
    virtual int callbackSquare(int& a) = 0;
    void doStuffWithCallBack();
};

void ABC::doStuffWithCallBack(){
    for(int i = 0; i < 10; ++i)
        m_results.push_back(std::async(&ABC::callbackSquare, this, i));

    for(int j = 0; j < 10; ++j)
        std::cout << m_results[j].get() << "\n";
}

class Derived : public ABC {
    Derived() : ABC() {};
    ~Derived(){};
    int callbackSquare(int& a) {return a * a;};
};

int main(int argc, char **argv)
{ …
Run Code Online (Sandbox Code Playgroud)

multithreading c++11 stdasync stdthread std-future

0
推荐指数
1
解决办法
47
查看次数