视觉工作室 - C++ 在后台重复一个功能
visual studio - C++ Have a function repeat in the background
我正在使用Microsoft Visual Express。
我已经查看了这个问题的已接受答案,它似乎没有做我想要它做的事情。
这是我每秒重复一次的功能:
double time_counter = 0;
clock_t this_time = clock();
clock_t last_time = this_time;
const int NUM_SECONDS = 1;
void repeat()
{
while (1)
{
this_time = clock();
time_counter += (double)(this_time - last_time);
last_time = this_time;
if (time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC))
{
time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
rockSecPast++;
}
}
}
我试图完成的是,在后台重复这一点。我的意思是我希望这个函数运行,但程序仍然继续其他函数并正常运行,这个函数总是在后台重复。
我尝试的是查看这个问题以寻找答案。但是我没有找到。
我的问题:我如何在后台重复一个函数,而程序仍然可以继续并与其他函数一起正常运行。一切应该仍然有效,但函数应始终在后台运行。
我也做了一些谷歌搜索,我发现的大部分内容都是连续重复,只运行该功能,而不继续其他功能。
将std::thread
与以下函数一起使用:
#include <thread>
void foo() {
// your code
}
int main() {
std::thread thread(foo);
thread.join();
return 0;
}
你想要的是我在评论中提到的std::thread
。但也要注意,您需要一种同步机制来防止全局变量的并发访问:
double time_counter = 0;
clock_t this_time = clock();
clock_t last_time = this_time;
const int NUM_SECONDS = 1;
std::mutex protect; // <<<<
void repeat() {
while (1) {
this_time = clock();
time_counter += (double)(this_time - last_time);
last_time = this_time;
if (time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC)) {
time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
std::lock_guard<std::mutex> lock(protect); // <<<<
rockSecPast++;
}
}
}
并在您的主线程中执行相同的操作
std::thread t(repeat);
t.detach();
// ....
int currentRockSecPast = 0;
{
// read the asynchronously updated value safely
std::lock_guard<std::mutex> lock(protect);
currentRockSecPast = rockSecPast;
}
如果我是你,我会把上面所有的混乱放在一个单独的班级里。
相关文章:
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 有没有可能有一个只有ADL才能找到的非好友功能
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 避免在条件更新时丢失唤醒是一个阻塞功能
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 通过将其中一个模板更改为 muliset 后,我可以在 PBDS 排序集上使用计数功能<int>less_equal<int>
- 有人可以展示一个使用多个功能的示例吗?
- 有没有办法C++将给定类的功能限制为仅另一个类(不使用继承,朋友)?
- 如何在一个功能中拥有所有选项?
- 使用一个功能打印最大值和平均值
- 如何简化代码并将开关组合成一个功能?
- 如何制作一个根据拉取请求关闭和打开功能的构建系统?
- 是否有一个Windows驱动程序函数可以执行Windows文件api SeFileAttributes的等效功能
- 如何使用 Turbo C++并行运行两个功能,一个用于键盘,一个用于鼠标?
- 维护/维持两个代码集的风险,一个用于 CPU,一个用于 GPU,需要执行非常相似的功能
- 当一个功能完成另一个功能打开时,我该怎么办?
- 别名一个模板函数,该功能没有参数可更简洁
- 编写一个递归功能,该功能采用数组并以相反顺序显示元素,而无需在末尾启动数组的索引
- 仅一个功能的链接错误.在同一类和CPP文件中具有相似签名的其他函数工作正常
- 调用两个功能(一个stdcall)的方法