c++ - 用螺纹产生旋转效果
问题描述
我是 C++ 新手,我想问一下如何解决下面给出的问题。我搜索了很多但没有得到合理的帮助。c ++的线程库可能会有所帮助。如何使用两个线程在屏幕的两个顶角显示两个旋转条。基本上每个线程都会驱动杆的“旋转”。(提示:您可以使用“\”和“/”来实现效果,但您必须弄清楚如何实现“旋转”的效果。)
解决方案
多线程的问题是您需要正确同步不同的线程,因为它们共享一个公共资源(控制台或 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;
}
推荐阅读
- php - JSON + PHP 错误不太清楚我做错了什么我正在关注视频教程。Uncaught SyntaxError: Unexpected token ] in JSON at position 0
- javascript - 如何在 React Native 中使用循环列出
- android - 关于 Android SDK 原生方法
- python - 将多个 .py 文件编译为 windows 可执行文件 (.exe)
- html - 背景图像封面不会缩小图像
- php - Laravel Entrust - 添加对访客角色的支持
- azure - 在哪里可以找到要在 Microsoft Flow 的 Azure REST API 调用中使用的受众和客户端 ID 字段?
- java - 使用 Java 遍历所有浮点值
- apache-spark - Spark - Spark DataFrame、Spark SQL 和/或 Databricks 表中的混合区分大小写
- python - PSQL 和 Django 2 的典型“关系“auth_user”不存在”