问题描述
我很难将参数传递给使用函数指针作为参数的调度队列。我已经实现了一个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()>
或{{ 1}}。应该没有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() ));
的使用期限。 -
或者,您可以使用lambda函数代替
engine
:std::bind
此方法和以前的方法在调用
AudioRecordEngine engine; queue->dispatch([&] { engine.run(mRecordingCallbackImp.getAudioData()); });
的时刻有所不同:在2中,getAudioData()
执行的结果存储在getAudioData()
返回的功能对象中,在3中,std::bind
在调用getAudioData()
之前被调用。