gpt4 book ai didi

c++ - 使用线程的意外行为

转载 作者:行者123 更新时间:2023-11-28 02:24:12 26 4
gpt4 key购买 nike

<分区>

我有一个函数,我想通过多线程对其进行优化。在 pBodies 中使用 Body 对象的整个 vector 调用函数 RenderBodies,就像我这样做的那样:

RenderBodies(pBodies);

我想调用它 4 次,每次使用 pBodies vector 的不同四分之一,并并行运行它们。

所以我像这样拆分 vector :

std::vector<Body*> Bodies1, Bodies2, Bodies3, Bodies4;

for (unsigned int i = 0; i < pBodies.size(); i += 4)
{
Bodies1.push_back(pBodies[i]);
Bodies2.push_back(pBodies[i + 1]);
Bodies3.push_back(pBodies[i + 2]);
Bodies4.push_back(pBodies[i + 3]);
}

然后使用带有新 vector 的线程,

std::thread t1(RenderBodies, pTarget, Bodies1, pZoom);
std::thread t2(RenderBodies, pTarget, Bodies2, pZoom);
std::thread t3(RenderBodies, pTarget, Bodies3, pZoom);
std::thread t4(RenderBodies, pTarget, Bodies4, pZoom);

t1.join();
t2.join();
t3.join();
t4.join();

但结果是什么都没有被渲染。

问题是,RenderBodies 函数没有任何问题,因为如果我使用这个函数:

RenderBodies(pTarget, Bodies1, pZoom);
RenderBodies(pTarget, Bodies2, pZoom);
RenderBodies(pTarget, Bodies3, pZoom);
RenderBodies(pTarget, Bodies4, pZoom);

有效!但它没有使用我 cpu 的所有 4 个内核,所以它没用。

为什么线程没有按预期工作?

我在 RenderBodies() 中的代码:

sf::RectangleShape Temp;

mtx.lock();
for (unsigned int i = 0; i < param.pBodies.size(); i++)
{
if (param.pZoom > 1)
Temp.setSize(sf::Vector2f(param.pBodies.at(i)->mass * param.pZoom, param.pBodies.at(i)->mass * param.pZoom));
else
Temp.setSize(sf::Vector2f(param.pBodies.at(i)->mass, param.pBodies.at(i)->mass));

float AccelCoefficient = static_cast<float> (sqrt(param.pBodies.at(i)->AccelX * param.pBodies.at(i)->AccelX + param.pBodies.at(i)->AccelY * param.pBodies.at(i)->AccelY) * (20000 * _GRAV_CONST));

if (AccelCoefficient > 1)
AccelCoefficient = 1;

float Red, Green, Blue;

Blue = 1 - (AccelCoefficient);

if (AccelCoefficient < 0.2)
Red = (AccelCoefficient)* 5;
else
Red = 1;

if (AccelCoefficient < 0.5)
Green = (AccelCoefficient)* 2;
else
Green = 1;

Temp.setFillColor(sf::Color(static_cast<sf::Uint8> (Red * 255), static_cast<sf::Uint8> (Green * 255), static_cast<sf::Uint8> (Blue * 255), 128));

Temp.setPosition(static_cast<float>(param.pBodies.at(i)->posX), (static_cast<float>(param.pBodies.at(i)->posY)));

param.pTarget->draw(Temp);
}
mtx.unlock()

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com