gpt4 book ai didi

c++ - 用线程产生旋转效果

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

我是 C++ 新手,我想问一下如何解决下面给出的问题。我搜索了很多但没有得到合理的帮助。c++的线程库可能会有所帮助。如何使用两个线程在屏幕的两个顶角显示两个旋转条。基本上每个线程都会驱动杆的“旋转”。 (提示:您可以使用“\”和“/”来实现效果,但您必须弄清楚如何实现“旋转”的效果。)

最佳答案

多线程的问题是您需要正确同步不同的线程,因为它们共享一个公共(public)资源(控制台或 GUI)。最好你会在一个线程中做这些事情:

uint32_t timestampLeft = getTimestamp(); // get high precision timestamp, at least
// ms (peak into <chrono> header for
// writing this function yourself;
// hint: make sure to use steady_clock!)
uint32_t timestampRight = getTimestamp();

for(;;)
{
uint32_t timestamp = getTimestamp();
if(timestampLeft - timestamp > PeriodLeft)
{
// exchange left symbol
// update console or GUI
timestampLeft = timestamp;
}
// right analogously
}
如果您坚持使用线程(或必须使用):
#include <cstdint>
#include <mutex>
#include <thread>

uint32_t constexpr PeriodLeft, PeriodRight; // TODO: initialize appropriately!
bool isRunning = true;
std::mutex mutex;

void run(uint32_t index, uint32_t period)
{
while(isRunning)
{
{
std::lock_guard g(mutex); // to avoid race conditions: lock the mutex

// update character/image for specific index
// redraw global/entire output

// mutex gets unlocked automatically as soon as guard leaves scope
}
// sleep for period
}
}

int main()
{
std::thread left(run, 0, PeriodLeft);
std::thread right(run, 1, PeriodRight);
// find out if we need to stop, then set isRunning to false
left.join();
right.join();
return 0;
}

关于c++ - 用线程产生旋转效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54385594/

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