【发布时间】:2016-07-05 18:03:46
【问题描述】:
所以,我让自己陷入了困境。我正在制作一种类似于示波器的程序,它分为一个主类、一个串行端口处理类和一个处理 FFT 实际性能的类。 Serial Handler 类使用 boost.Asio 的异步读取功能从串行端口读取数据,然后我想将这些数据传递给 FFT 处理类的成员函数。该设置非常适合阅读。我有一个 io_service 对象在一个单独的线程上运行,当有数据要读取时,它会调用一个事件处理程序。
这就是问题所在。不知何故,我需要找到一种方法将数据从 async_read_some 的事件处理程序传递到一个单独的类的方法,该类也恰好位于另一个线程上。我什至不知道这是否可能完全诚实。虽然这两个类确实存在于 main 方法中,所以我认为可以在它们之间传递数据。即使这是不可能的,有什么方法可以达到预期的效果?我想最坏的情况可能会将它们合并到一个类中。
编辑:这里有一些快速的伪代码,只是为了更好地了解所有这些如何链接在一起。免责声明:我不完全确定如何正确编写伪代码,我是一个有点自私的程序员,所以如果它不是太容易理解,请告诉我,我会看看我能做些什么来解决它:
//declared globally
boost::mutex mutex_;
sem_t qSem;
queue q;
class SerialHandler{
private:
string portName;
public:
void StartConnection(){
//...some initialization things
AsyncReadSome();
//thread is initiated here
t1 = new boost::thread(boost::bind(&boost::asio::io_service::run, &ioService));
}
//the only important thing here is it reads into a buffer and calls the event after the read
void AsyncReadSome(){
serialPort->async_read_some(boost::asio::buffer(rawBuffer, SERIAL_PORT_READ_BUFF_SIZE),
boost::bind(&SerialHandler::HandlePortOnReceive,
this, placeholders::error,
placeholders::bytes_transferred, q));
}
void HandlePortOnReceive( error_code &ec, size_t bytes_transferred, queue q){
scoped_lock (mutex_); //from boost lib
for (int i=0;i<bytes_transferred;i++){
double d = (double) rawBuffer[i]; //pushes data into queue
q.push(c);
sem_post(&qSem);
}
AsyncReadSome(); //loops back on itself
}
}
class FFTHandler{
private:
double *in; //holds the input array
fftw_complex *out;//holds out array
int currentIndex;
public:
void AppendIn(queue &q, sem_t &_qSem){
while (1){
sem_wait(&_qSem);
double d = q.pop();
in[currentIndex] = d;
if (...){}//some logic to not overflow the in[]
}
}
}
int main(){
FFTHandler fftHandler;
SerialHandler serialHandler;
//...some initialization of global variables goes here
serialHandler.StartConnection();
boost::thread *t2=new boost::thread(boost::bind(&FFTHandler.AppendIn, &fftHandler, &q, &qSem);
char c = getchar();
if (c){call stop functionality}
}
【问题讨论】:
-
你看boost signals了吗?
-
@mvidelgauz 我从来没有使用过 boost::signals2 所以你必须原谅我的无知,但是,从我对文档和教程的阅读来看,我不完全确定如何我将能够使用它将数据从事件处理程序传递到我的主线程上的类。您介意详细说明吗?
-
抱歉,目前没有我的旧项目代码。如果到明天晚上没有人会回答,我会尝试找到代码示例。同时,您也可以搜索它(也许使用“site:stackoverflow.com”:-))。我敢肯定有很多
标签: c++ multithreading oop events boost-asio