我最近在 Conway 的 Game of Life 中创建了一个模式搜索程序,但运行速度太慢,不实用。
所以我决定并行化它,但我失败了;它导致了分段错误,这很可能是由于数据竞争。
代码的简要说明:
/* ... */
#include <list>
#include <mutex>
#include <future>
#include <iostream>
#include <forward_list>
int main() {
/* ... */
while (true) {
/* ... */
std::forward_list</*pattern type*/> results;
std::list<std::future<void>> results_future;
std::mutex results_mutex;
for (/*All the possible unique pattern in given grid*/)
results_future.push_back(std::async([&]{
/*A very hard calculation*/
if (/*The pattern is what I'm looking for*/) {
std::lock_guard<std::mutex> results_guard(results_mutex);
results.push_front(std::move(/*The pattern*/));
}
}));
while (!results_future.empty()) {
results_future.front().wait();
results_future.pop_front();
}
if (!results.empty()) {
for (auto &res : results)
std::cout << "Pattern found:" << std::endl << res;
return 0;
}
}
}
我很确定results
这是在 lambda 表达式的函数范围之外声明并在那里修改的唯一对象,所以我用互斥锁锁定了它。
但数据竞赛仍然存在。那么是什么原因造成的呢?