使用C++编程,也许我的思绪仍然停留在90年代,无法绕过一些概念请帮助我.
所以正在使用gtkmm进行开发,并遇到了一些多线程示例,就像这样
class ExampleWorker {
public:
void do_work(ExampleWindow* caller);
private:
mutable std::mutex m_Mutex;
};
ExampleWindow::ExampleWindow(){
ExampleWorker m_Worker;
std::thread* m_WorkerThread;
void ExampleWindow::on_start_button_clicked() {
if (blablabla){
blablabla
} else {
// Start a new worker thread.
m_WorkerThread = new std::thread(/////////////lambda function
[this] // <==== let this this be "this-A"
{
m_Worker.do_work(this); // let this this be "this-B"
}///////////////end of lambda function /////////////
);
}
Run Code Online (Sandbox Code Playgroud)
我理解的主要问题是lambda部分.所以首先lambda概念对我来说是个新鲜事,在C++中查找"捕获"的概念却没有找到太多,所以我最好的猜测是,在这种情况下,它允许我"捕获"" [this]"根据文档返回的内容,似乎是[this] captures the this pointer by value
指向作为线程指针的工作者的指针,因为工作程序包含互斥锁.
但是我不明白的是,对我来说,"this-B"似乎表明"this"正在将ExampleWindow对象本身传递给函数,正如Worker类所定义的那样,它应该将调用者传递给它; 请问"this-A"似乎能够引用工作线程本身.问题,这是否意味着lambda函数捕获[this]在这种情况下,取代正常的"this",它引用调用对象,如"this-B"?
更多关于lambda的事情,我一直努力理解的另一个例子来自boost asio.
//definition
void async_read_some(
const …
Run Code Online (Sandbox Code Playgroud)