这个线程类使用模板实现了参数的传递,第一次知道结构体还可以传递指针和引用
先来看这个传递的参数
struct SensorThreadParams
{
zen::ZenClient * zenClient;
std::string frame_id;
std::string frame_id_gnss;
ros::Publisher & imu_pub;
ros::Publisher & mag_pub;
ros::Publisher & nav_pub;
bool useLpmsAccelerationConvention;
ZenComponentHandle_t zen_imu_component;
ZenComponentHandle_t zen_gnss_component;
};
再来看这个函数是如何写的
#ifndef MANAGED_THREAD_H
#define MANAGED_THREAD_H
#include <functional>
#include <thread>
#include <atomic>
template <class TThreadParameter>
class ManagedThread {
public:
typedef std::function<bool(TThreadParameter)> WorkerFunction;
ManagedThread() {}
ManagedThread(WorkerFunction func) : m_func(func) {
}
~ManagedThread() {
stop();
}
bool start(TThreadParameter threadParams) {
if (m_workerThread.joinable()) {
// cannot start while thread is running
return false;
}
m_terminate = false;
//使用引用来控制线程中的状态
auto & terminateLocal = m_terminate;
WorkerFunction workerLocalCopy = m_func;
// capture by copy so we are independent of the lifetime of the
// thread parameters
//这里定义了一个函数,作为thread初始化的参数
const auto lmdWrapperManager = [threadParams,
&terminateLocal,
workerLocalCopy](){
while (! terminateLocal.load()) {
// exit if the thread worker code requested it
if (!workerLocalCopy(threadParams))
return;
}
};
m_workerThread = std::thread(lmdWrapperManager);
return true;
}
void stopAsync() {
m_terminate = true;
// don't join explicitly
}
/**
\param waitForThreadTerminate if true, the thread loop will not
terminate after the next execution round but the class
will wait until the worker lambda returned false.
*/
void stop(bool waitForThreadTerminate = false) {
m_terminate = !waitForThreadTerminate;
// join the worker thread, so we can be sure that
// it terminated
if (m_workerThread.joinable()) {
m_workerThread.join();
}
}
bool isRunning() const {
return m_workerThread.joinable();
}
private:
WorkerFunction m_func;
std::thread m_workerThread;
std::atomic<bool> m_terminate;
};
#endif
这是使用
m_sensorThread.start( SensorThreadParams{
m_zenClient.get(),
frame_id,
frame_id_gnss,
imu_pub,
mag_pub,
nav_pub,
m_useLpmsAccelerationConvention,
zen_imu_component,
zen_gnss_component
} );
这是写了多少代码的老鬼的杰作,感觉不怎么舒展,毕竟写代码是让别人看懂的嘛