c++ std::future 在单独的核心上运行每个函数

标签 c++ multiprocessing future

这是一个在四核 Cortex A9 ARMv7(Linux 和 gcc 4.8.2)上运行的实时音频应用程序,这是处理实际音频(通过调用其他函数)并发送到音频的部分司机:

struct STEREOOUT
{
    std::vector<float> L;
    std::vector<float> R;
};

STEREOOUT ProcessEngine(int e, unsigned int sf)
{
    STEREOOUT out;
    for (unsigned int s=0; s<sf; ++s)
    {
        float l, r; 
        engine[e]->Process(l, r);
        out.L.push_back(l);
        out.R.push_back(r);
    }
    return out;
}

// This is the main audio loop callback!
int AudioProcess(void *outputBuffer, unsigned int sampleFrames)
{
    float *buffer = (float*)outputBuffer;
    unsigned int s(0);

    STEREOOUT e0 = async(launch::async, &ProcessEngine, 0, sampleFrames).get();
    STEREOOUT e1 = async(launch::async, &ProcessEngine, 1, sampleFrames).get();

    for (; s<sampleFrames; ++s)
    {
        *buffer++ = e0.L[s] + e1.L[s];
        *buffer++ = e0.R[s] + e1.R[s];
    }

    return 0;
}

我如何确保 e1e2 以与 main() 程序不同的亲和性运行,但它们之间又有所不同?例如:

main() -> CPU0
e1 -> CPU1
e2 -> CPU2

我的代码,如您在此处看到的那样编译后,似乎仍然在单核上运行。我需要两个音频处理占用两个不同的内核,以便利用四核处理器的全部功能。我是在做梦吗?

P.S.:我知道,我过去已经发布过类似的问题,但这次我可以更精确,因为我现在有一个完成的工作程序,我可以将其用作实际示例。

最佳答案

您在调用 std::async 之后立即调用 get,这将导致程序等待结果可用。 在等待它们之前,您需要启动两个异步任务:

auto future1 = async(launch::async, &ProcessEngine, 0, sampleFrames);
auto future2 = async(launch::async, &ProcessEngine, 1, sampleFrames);

STEREOOUT e0 = future1.get();
STEREOOUT e1 = future2.get();

关于c++ std::future 在单独的核心上运行每个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29602603/

相关文章:

c++ - 使用 CURL 从 HTTPS 连接中获取任何内容

c++ - 指向堆栈变量的指针应该是易变的吗?

c++ - 在 C++ 中访问重载运算符

python - 按顺序执行ProcessingPools的正确方法

python - 使用 concurrent.futures 一次消耗许多出队消息

asynchronous - 即使范围拥有变量的所有权,引用仍被保留而无法使用

Python:WAITING所有 `concurrent.futures.ThreadPoolExecutor` 的 future

c++ - 在 C++ 中使用正则表达式查找 [/和 ] 之间的数字

dart - StreamBuilder 限制

python - 从多处理 python 函数中提取输出