我很难将参数传递给使用函数指针作为参数的调度队列。我已经实现了像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
似乎我的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;
}
最佳答案
DispatchQueue
实现的内部,将fp_t
类型的功能对象作为fn()
调用,因此fp_t
应该是std::function<std::string()>
或std::function<void()>
。不应有const std::array&
参数。std::bind
应该给您一些不带参数的东西。您的std::bind
几乎是正确的。当您要调用非静态成员函数时,需要一个对象。该对象以指针或引用的形式应为std::bind
的第二个参数:AudioRecordEngine engine;
queue->dispatch(std::bind(
&AudioRecordEngine::run,
std::ref(engine),
mRecordingCallbackImp.getAudioData()
));
请注意engine
的使用时间。std::bind
:AudioRecordEngine engine;
queue->dispatch([&] {
engine.run(mRecordingCallbackImp.getAudioData());
});
此方法和先前的方法在调用getAudioData()
时有所不同:在2中,getAudioData()
执行的结果存储在std::bind
返回的功能对象内部,在3中,在调用getAudioData()
之前调用run
。Minimal example
关于c++ - 在运行时将参数传递给std::bind到调度队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63544275/