[英]C++11: Segfault with std::thread and lambda function
我寫了一個小應用程序來演示這個問題,它並不漂亮,但它完成了工作。
#include <functional>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
class A {
public:
A() : thread_(), tasks_(), mutex_(), a_(99999) {}
void Start() {
thread_ = std::thread([this] () { Run(); });
}
private:
using Task = std::function<void()>;
public:
void AddTask(const Task& task) {
std::lock_guard<std::mutex> lock(mutex_);
tasks_.push(task);
}
bool Empty() {
std::lock_guard<std::mutex> lock(mutex_);
const bool empty = tasks_.empty();
return empty;
}
Task GetTask() {
std::lock_guard<std::mutex> lock(mutex_);
const auto& task = tasks_.front();
tasks_.pop();
return task;
}
int GetInt() { return a_; }
void Join() { thread_.join(); }
private:
void Run() {
while (Empty());
(GetTask())();
}
std::thread thread_;
std::queue<Task> tasks_;
std::mutex mutex_;
int a_;
};
template <class Base>
class B : public Base {
public:
using Base::Base;
void Start() {
Base::Start();
std::cout << "A: " << this << std::endl;
Base::AddTask([this] () { std::cout << "T: " << this << std::endl; Do(); });
}
void Do() {
std::cout << "Do: " << this << std::endl;
std::cout << "GetInt: " << Base::GetInt() << std::endl;
}
};
int main() {
B<A> app;
app.Start();
app.Join();
}
clang++ -std=c++11 -lpthread test_a.cpp
A: 0x7ffeb521f4e8
T: 0x21ee540
Do: 0x21ee540
GetInt: 0
注意'this'的變化和'GetInt'的值0。
我真的在這里迷路了......任何幫助將不勝感激,
謝謝。
我將您的復制減少到:
#include <functional>
#include <iostream>
#include <queue>
struct foo {
using Task = std::function<void()>;
void Test() {
std::cout << "In Test, this: " << this << std::endl;
AddTask([this] { std::cout << "In task, this: " << this << std::endl; });
}
void AddTask(const Task& task) {
tasks_.push(task);
}
Task GetTask() {
const auto& task = tasks_.front();
tasks_.pop();
return task;
}
std::queue<Task> tasks_;
};
int main() {
foo f;
f.Test();
auto func = f.GetTask();
func();
}
你現在看到問題了嗎? 問題在於:
const auto& task = tasks_.front();
tasks_.pop();
在這里,您獲取對對象的引用,然后告訴隊列繼續並刪除該對象。 您的參考現在懸而未決,隨之而來的是混亂。
您應該將其移出:
Task GetTask() {
auto task = std::move(tasks_.front());
tasks_.pop();
return task;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.