1

我正在尝试在 folly::ThreadedExecutor 中添加一些正常的工作,这些工作是 folly::Function。但是,folly::ThreadedExecutor 似乎只提供了接受的接口folly::Function<void()>。如何添加带有参数和输出的函数?

// Here's a simple code segment

#include <folly/executors/ThreadedExecutor.h>
#include <folly/futures/Future.h>

int my_func(int t) {
   sleep(t);
   return 1;
}

int main() {
   folly:ThreadedExecutor executor;
   folly:Function<int(int)> job = my_func;
   executor.add(job);  
}

编译gcc -o folly_executor --std=c++14 -g -O0 -Wall folly_executor.cc -lgtest -lfolly -lpthread -lglog -lgflags -ldl -ldouble-conversion -levent -liberty -lboost_context

该错误表示 和 中的函数 add原型不匹配。以下是编译错误。executormy_func

In file included from folly_executor.cc:2:0:
/usr/local/include/folly/executors/ThreadedExecutor.h:67:8: note: 
candidate: virtual void folly::ThreadedExecutor::add(folly::Func)
   void add(Func func) override;
        ^~~
/usr/local/include/folly/executors/ThreadedExecutor.h:67:8: note:   no 
known conversion for argument 1 from 'folly::Function<int(int)>' to 
'folly::Func {aka folly::Function<void()>}'

我想知道添加函数原型的限制是否有必要的原因。如果不是,它必须是正确的方法。

顺便说一句,Github 上的教程和文档总是使用 folly::executor 和 folly:Future。我应该以这种方式使用 folly:Function 吗?

4

2 回答 2

1

感谢 Alex Bakulin 的回答。我用接口解决了我的问题folly::Future,以下是我的示例代码。在我的情况下,我Future一起使用AtomicHashMap。使用Future和 可以轻松地提供输入和访问folly::via输出std::bind。但是,我仍然对为什么他们缩小使用范围Folly::Function并期望它仅用于存储可调用对象而没有任何输入和输出感到困惑。

#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/futures/Future.h>
#include <folly/AtomicHashMap.h>


folly::Future<int> my_func(int t, folly::AtomicHashMap<int, int>& ahm) {
    ahm.insert(std::make_pair(t, t*2));
    return 1;
}

int main() {
    folly::CPUThreadPoolExecutor executor(8);
    folly::AtomicHashMap<int, int> ahm(4096);
    for (int i = 0; i < 3; i++) {
        folly::Future<int> f = folly::via(&executor, std::bind(my_func, i, std::ref(ahm)));
    }
    executor.join();

    for (int i = 0; i < 3; i++) {
        auto ret = ahm.find((i));
        int r = ret != ahm.end() ? ret->second : 0;
        std::cout << i << "th result is "<< r << std::endl;
    }
    return 0;
}
于 2018-11-01T06:02:28.177 回答
0

您可能已经自己弄清楚了,但为了完整起见,我会给出一个答案。ThreadedExectutor是一个非常低级的东西,它只是在单独的线程中为你运行东西。当您安排某个函数运行时,您无法控制它返回的时间和内容。如果您需要做的只是让函数调用发生在一个单独的线程中,您可以将此调用包装在一个匿名函数中,并使用执行程序期望的签名:

executor.add([]() { my_func(123); });

如果您的目标也是捕获调用的输出,那么您最好使用futures,它处于更高的抽象级别,并为您提供更丰富的原语集来使用。

于 2018-10-31T16:29:50.103 回答