在运行时将参数传递给std :: bind到调度队列

问题描述

我很难将参数传递给使用函数指针作为参数的调度队列。我已经实现了一个this tutorial

这样的调度队列
typedef std::function<std::string( const std::array<float,kMaxSamples> &)> fp_t;


class DispatchQueue {
public:
    DispatchQueue(std::string name,size_t thread_cnt = 1);
    ~DispatchQueue();
    //move
    void dispatch(fp_t && item); //Take the typedef defined above

private:

    std::string _name;
    std::queue<fp_t> _q;
    std::vector<std::thread> _threads;
    void dispatch_thread_handler(void);
    std::mutex _lock;
    std::condition_variable _cv;
    bool _quit;
};

我的std :: function以std :: array作为参数。

然后,稍后在我的代码中,我在队列中添加该特定作业以处理该参数。

queue->dispatch(std::bind(&AudioRecordEngine::run,mRecordingCallbackImp.getAudioData()));

调度功能定义为:

void DispatchQueue::dispatch(fp_t &&item)
{
   std::unique_lock<std::mutex> lock(_lock);

    _q.push(item);

    // Manual unlocking is done before notifying,to avoid waking up
    // the waiting thread only to block again (see notify_one for details)
    lock.unlock();
    _cv.notify_one();
}`

对于这个用例来说可能太复杂了,我可能不知道如何做得更好。

我将非常感谢您的建议和帮助。我被困了很长时间。

非常感谢

编辑: 我面临的问题是在编译时:

没有从'__bind (AudioRecordEngine :: *)的可行转换(const std :: __ ndk1 :: array &),std :: __ ndk1 :: array >>到'fp_t'(aka'function ( const array &)>')

似乎我的std :: function不支持我传递的参数。问题看起来好像我没有正确使用std :: bind。

基本上,我想将带有给定参数的函数指针传递给我的调度函数。

编辑2:

AudioRecordEngine :: run定义为:

   std::string AudioRecordEngine::run(const std::array<float,__NUM_SAMPLES__> & audioData) {
    std::thread::id this_id = std::this_thread::get_id();
    LOGD("In the thread ID %zu  \n",this_id);
    //double freq = FFTNativeWrapper::fftEntryPoint(audioData);
    //LOGD("In the Thread,FFT analysis == %zu  \n",freq);
    return "from thread";
}


std::array<float,kMaxSamples> RecordingCallbackImp::getAudioData() {
return mData;

}

解决方法

  1. DispatchQueue的实现中,类型fp_t的功能对象被称为fn(),因此fp_t应该是std::function<std::string()>或{{ 1}}。应该没有std::function<void()>参数。

  2. const std::array&应该给您一些不带参数的东西。您的std::bind几乎是正确的。当您要调用非静态成员函数时,需要一个对象。该对象以指针或引用的形式应为std::bind的第二个参数:

    std::bind

    请注意AudioRecordEngine engine; queue->dispatch(std::bind( &AudioRecordEngine::run,std::ref(engine),mRecordingCallbackImp.getAudioData() )); 的使用期限。

  3. 或者,您可以使用lambda函数代替engine

    std::bind

    此方法和以前的方法在调用AudioRecordEngine engine; queue->dispatch([&] { engine.run(mRecordingCallbackImp.getAudioData()); }); 的时刻有所不同:在2中,getAudioData()执行的结果存储在getAudioData()返回的功能对象中,在3中, std::bind在调用getAudioData()之前被调用。

Minimal example

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...