【发布时间】:2020-03-31 20:10:34
【问题描述】:
我是多线程新手,已经开始遇到问题。 我想在一个类函数上实现 10 个线程重用,它的父类在 while 循环中有 4 个函数,但它给了我像 "error C3867: 'std::thread::join 这样的错误':非标准语法;使用 '&' 创建指向成员的指针" 和 "std::system_error at memory location" 由于我不知道我解释得有多好,我将向您展示我想要实现的伪代码: 主.cpp
Game newGame;
/* Create Players */
Population pop(NumberOfPlayers);
/* Create Enemies */
std::vector<Enemies> enemy;
for (int i = 0; i < NumberOfEnemies; i++) {
Enemies e(i);
enemy.push_back(e);
}
while (!pop.hasFinished) {
std::thread threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = std::thread(std::bind(&Population::populationMove, &pop, (i * NumberOfPlayers / NUM_THREADS)));
//std::cerr << "In Thread " << i << "\n";
}
for (int i = 0; i < NUM_THREADS; i++) {
if(threads[i].joinable)
threads[i].join;
//std::cerr << "In Thread " << i << "\n";
}
for (int i = 0; i < NumberOfEnemies; i++) {
enemy[i].movement();
enemy[i].checkIfKills();
}
enemymoves++;
if (pop.checkIfAllDead()) {
pop.calculateBest();
pop.createNewPopulation();
for (int i = 0; i < NumberOfEnemies; i++) {
if ((pop.gen - 1) % 5 == 0) {
enemy[i].save();
}
enemy[i].reset();
}
}
}
这是populationMove()的伪代码
Population::populationMove(int threadStartIndex) {
for (int i = threadStartIndex; i < threadStartIndex + (player.size() / NUM_THREADS); i++) {
mtx.lock();
player[i].move();
mtx.unlock();
}
【问题讨论】:
-
也许尝试将
std::thread threads[N_THREADS];放在while 循环中而不是放在外面? -
在询问构建错误或消息时,请包含一个实际的minimal reproducible example,我们可以使用它来复制错误。并且始终包含该示例中的实际错误消息,完整且完整地复制粘贴(并且复制粘贴为文本,而不是图像)。并在代码中添加 cmets 以显示错误所在。另外请花一些时间阅读how to ask good questions和this question checklist。
-
"错误 C3867: 'std::thread::join': 非标准语法;使用 '&' 创建指向成员的指针"
-
有一个错字,开头是:
= std::thread(&Class::classFunction, &classObject, threadindex);-- 不应该有大括号。 -
首先将 full 和 complete 错误输出复制粘贴到问题本身。然后显示导致错误的实际代码,而您没有。
标签: c++ multithreading