多线程的实现方式,只做记录,自己看。
目录
- 第一种 在类中实现多线程
- 第二种 在类外
- 第三种 没有类
- 第四种 pthread,定时触发
- 总结
- 附录
第一种 在类中实现多线程
新建thread对象,传入类的成员函数名称,对象地址,以及成员函数需要的参数。
在类的成员函数中,要实现多线程
void Perception::test()
{
.....
thread th( &Perception::showImage, this);
.....
}
void Perception::showImage();
如果showImage()要传参数,就在this后面加上。
如果Perception中有另外一个成员,叫做mapOptimization,如果线程函数是mapOptimization的成员函数,
LidarMapping::mapOptimization::loopClosureThread
unique_ptr loopThread = std::make_unique<std::thread>(&mapOptimization::loopClosureThread,this->MO_);
会出问题
要把mapOptimization::loopClosureThread 封装成LidarMapping 的一个函数loopClosure:
loopThread = std::make_unique<std::thread>(&LidarMapping::loopClosure,this);
第二种 在类外
在主函数中,
void main()
{
A a;
thread th(&A::test,&a);
}
第三种 没有类
void func()
{
.....
}
void main()
{
A a;
thread th(func);
}
第四种 pthread,定时触发
使用定时器触发,传入多个参数。
定时器实现是在回调函数中的:
double process_time = double(clock() - time_start) / CLOCKS_PER_SEC * 100;
pthread_testcancel();
struct timeval tempval;
tempval.tv_sec = 0;
tempval.tv_usec = 100000;
select(0, NULL, NULL, NULL, &tempval);
其中,多个参数的定义在TIMECALL(结构体),先对结构体成员进行实例化、赋值,然后在将timecall(取地址)传入。
TIMECALL timecall;
timecall.log = &log_data;
timecall.outdata = &serial_output;
timecall.udp_output = &udp_output;
timecall.threadPerception = &per;
timecall.m_LogFile = &file_check;
void main()
{
TIMECALL timecall;
timecall.log = &log_data;
timecall.outdata = &serial_output;
timecall.udp_output = &udp_output;
timecall.threadPerception = &per;
timecall.m_LogFile = &file_check;
pthread_t id;
int i, ret;
ret = pthread_create(&id, NULL, thread_cb, (void *)&timecall);
}
typedef struct TIMECALL_
{
Log *log;
result_serial::perception_result_serial *outdata;
UDPSocket *udp_output = nullptr;
perception::Perception *threadPerception = nullptr;
FileManage *m_LogFile= nullptr;
FileManage *m_RosLog = nullptr;
} TIMECALL;
void *thread_cb(void *p)
{
TIMECALL *arg = (TIMECALL *)p;
clock_t time_start = clock();
while (true)
{
perception_output = arg->threadPerception->getOutdata();
arg->udp_output->UDPSocket::Send((char *)&perception_output, sizeof(perception_output));
arg->log->toFile((unsigned char *)&perception_output, sizeof(perception_output));
arg->m_LogFile->Start();
double process_time = double(clock() - time_start) / CLOCKS_PER_SEC * 100;
pthread_testcancel();
struct timeval tempval;
tempval.tv_sec = 0;
tempval.tv_usec = 100000;
select(0, NULL, NULL, NULL, &tempval);
}
}
总结
1.形式都是类似的,定义thread,然后在构造函数或者pthread_creat函数中将要处理的函数及参数放进去
2.pthread要放静态函数。对于静态函数的处理,尤其是对于类的非静态成员函数的处理要留意,这部分后续补充。目前采用的办法是thread th(&类名::函数名,对象地址,参数)的方式。
3.之前做java的时候,好像是继承Thread类,重写run函数,还有runable接口,好像在C+里面不怎么使用这种方式,后续遇到再补充。
附录
几篇博客:
C++多线程的实现
C++多线程详细讲解
C++ 多线程编程之在类中使用多线程(thread)的方法
C++多线程编程之thread类
C++ 在类里面使用多线程技术
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)