成员函数中std:Thread初始化

8 篇文章 0 订阅

目前对c++多线程理解还不是很深入,主要是在看《c++并发编程》,在书中初始化一个线程:

void	do_some_work();
std::thread	my_thread(do_some_work);

这个也很好理解,在初始化的时候传入do_some_work函数的指针。
但是在看ceph代码看到Timer类中的std::Thread 初始化方式有点不理解。

 55     class timer {
 ........
 112       void timer_thread() {
 113         unique_lock l(lock);
 114         while (!suspended) {
 115           typename TC::time_point now = TC::now();
 116 
 117           while (!schedule.empty()) {
 118             auto p = schedule.begin();
 119             // Should we wait for the future?
 120             if (p->t > now)
 121               break;
 122 
 123             event& e = *p;
 124             schedule.erase(e);
 125             events.erase(e);
 126 
 127             // Since we have only one thread it is impossible to have more
 128             // than one running event
 129             running = &e;
 130 
 131             l.unlock();
 132             e.f();
 133             l.lock();
 134 
 135             if (running) {
 136               running = nullptr;
 137               delete &e;
 138             } // Otherwise the event requeued itself
 139           }
 140 
 141           if (schedule.empty())
 142             cond.wait(l);
 143           else
 144             cond.wait_until(l, schedule.begin()->t);
 145         }
 146       }
 147 
 148   public:
 149       timer() {
 150         lock_guard l(lock);
 151         suspended = false;
 152         thread = std::thread(&timer::timer_thread, this);
 153       }
 ..........

其中在timer的构造函数中std::thread的参数不仅有timer_thread的指针还传入了this指针。完全不理解为什么需要这个this指针啊。后来请教一下C++大神才理解,每个类的成员函数有一个隐藏的this指针形参,所以这里的this指针是timer_thread的形参。

 149       timer() {
 150         lock_guard l(lock);
 151         suspended = false;
 152         thread = std::thread(&timer::timer_thread, this);
 153       }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值