首页 > 解决方案 > 用螺纹产生旋转效果

问题描述

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

标签: c++multithreading

解决方案


多线程的问题是您需要正确同步不同的线程,因为它们共享一个公共资源(控制台或 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;
}

推荐阅读