我是C ++的新手,我想问一下如何解决以下给定的问题。我进行了很多搜索,但没有得到合理的帮助.c ++的线程库可能会有所帮助。如何使用两个线程在屏幕的两个上角显示两个旋转的条形图。基本上,每个线程都会驱动杆的“旋转”。 (提示:您可以使用“ \”和“ /”来实现效果,但必须弄清楚如何实现“旋转”效果。)
答案 0 :(得分:0)
多线程问题是您需要正确同步不同的线程,因为它们共享一个公共资源(控制台或GUI)。最好在一个线程内完成这些工作:
uint32_t timestampLeft = getTimestamp(); // get high precision timestamp, at least
// ms (peak into <chrono> header for
// writing this function yourself)
uint32_t timestampRight = getTimestamp();
for(;;)
{
uint32_t timestamp = getTimestamp();
if(timestampLeft - timestamp > PeriodRight)
{
// 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;
}