我找不到写一个好的条件来解决我的问题的方法。正如您在包含的图像中看到的那样,屏幕中间有一条线,球无休止地上下移动并在一段时间后消失。新球也层出不穷。
我的任务是使用互斥锁,这样只有 N 个球(2 个或 3 个)可以在线上,其余的都在等待轮到他们。
我尝试了几个选项,这是最近的一个。这可能没有多大意义,但我目前没有其他想法:
来自 ball.cpp 的片段:
Ball::Ball(int nr)
{
this->nr = nr;
changeDirection();
this->x = 40;
this->y = 24;
this->lastX = 0;
this->lastY = 0;
this->bounceCounter = 0;
this->isAboveTheLine = false;
}
...........
if(y < 12) {
isAboveTheLine = true;
}
else if(y >= 12) {
isAboveTheLine = false;
}
并来自 main.cpp:
std::mutex m;
void ballFunction(int a)
{
int counter = 2;
int nr = a;
while (run && shared->balls[nr]->bounceCounter < 5)
{
usleep(50000);
shared->balls[nr]->updateBall();
if(shared->balls[nr]->isAboveTheLine == true) {
counter++;
}
else if(shared->balls[nr]->isAboveTheLine == false) {
counter--;
}
if(counter >= 3) {
m.lock();
}
else if (counter<2) {
m.unlock();
}
}
shared->balls[nr]->x = -1;
shared->balls[nr]->y = -1;
}
编辑:我添加了 int main():
int main() {
srand(time(NULL));
window = new Window();
int i = 0;
std::vector<std::thread> threads;
std::thread threadWindow(updateWindow2);
std::thread threadExit(exit);
while(run) {
window->addBall();
threads.push_back(std::thread(ballFunction, i));
i++;
sleep(1);
}
threadWindow.join();
threadExit.join();
for(int j=2; j<i+2; j++) {
threads[j].join();
}
return 0;
}
它根本不起作用。我是朝着正确的方向前进还是需要不同的方法?