Commit 0647a241ac526314c7e2256dcfa8c34506ac148c
1 parent
a99b00d6
fix(connection): thread could access members before constructor was done initializing
By delaying the thread creation to inside the body of the constructor this is solved. That way, the contructor is already done initializing all member variables, and the threads can start safely. Otherwise you could see weird errors depending on how fast the threads started.
Showing
1 changed file
with
6 additions
and
2 deletions
src/Connection.cpp
| ... | ... | @@ -18,10 +18,14 @@ |
| 18 | 18 | |
| 19 | 19 | TrueMQTT::Client::Impl::Connection::Connection(Client::Impl &impl) |
| 20 | 20 | : m_impl(impl), |
| 21 | - m_thread_read(&Connection::runRead, this), | |
| 22 | - m_thread_write(&Connection::runWrite, this), | |
| 23 | 21 | m_backoff(impl.m_connection_backoff) |
| 24 | 22 | { |
| 23 | + // This has to be delayed to inside the ctor body, as otherwise other | |
| 24 | + // parts of the object might not been initialized yet, and the threads | |
| 25 | + // might already start running (and using these not initialized parts). | |
| 26 | + m_thread_read = std::thread(&Connection::runRead, this); | |
| 27 | + m_thread_write = std::thread(&Connection::runWrite, this); | |
| 28 | + | |
| 25 | 29 | pthread_setname_np(m_thread_read.native_handle(), "TrueMQTT::Read"); |
| 26 | 30 | pthread_setname_np(m_thread_write.native_handle(), "TrueMQTT::Write"); |
| 27 | 31 | } | ... | ... |