Skip to content

Commit 4f349ba

Browse files
committed
Use one timer and thread for seria port read
1 parent dc4f16a commit 4f349ba

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

qt/serial_port.cpp

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
SerialPort::SerialPort()
1010
{
11+
timer = timer_ptr(new boost::asio::deadline_timer(ioService));
1112
}
1213

1314
SerialPort::~SerialPort()
@@ -101,18 +102,20 @@ int SerialPort::asyncReadWithTimeout(char *buf, int size,
101102

102103
readCb = cb;
103104

105+
timer->expires_from_now(boost::posix_time::seconds(timeout));
106+
timer->async_wait(boost::bind(&SerialPort::onTimeout, this,
107+
boost::asio::placeholders::error));
108+
104109
port->async_read_some(boost::asio::buffer(buf, size),
105110
boost::bind(&SerialPort::onReadWithTimeout, this,
106111
boost::asio::placeholders::error,
107112
boost::asio::placeholders::bytes_transferred));
108113

109-
timer = timer_ptr(new boost::asio::deadline_timer(ioService));
110-
timer->expires_from_now(boost::posix_time::seconds(timeout));
111-
timer->async_wait(boost::bind(&SerialPort::onTimeout, this,
112-
boost::asio::placeholders::error));
113-
114-
thread = thread_ptr(new boost::thread(boost::bind(&boost::asio::
115-
io_service::run, &ioService)));
114+
if (!thread)
115+
{
116+
thread = thread_ptr(new boost::thread(boost::bind(&boost::asio::
117+
io_service::run, &ioService)));
118+
}
116119

117120
return 0;
118121
}
@@ -121,7 +124,6 @@ void SerialPort::onReadWithTimeout(const boost::system::error_code &ec,
121124
size_t bytesRead)
122125
{
123126
timer->cancel();
124-
timer = nullptr;
125127

126128
if (ec)
127129
{

0 commit comments

Comments
 (0)