C++ - 不断递增一个整数

标签 c++ increment

我正在寻找一种让整数每 10 秒左右不断递增的方法。我知道如何让整数递增,但我不知道如何让它继续递增,而不管程序的其余部分当前发生了什么。

最佳答案

为此使用 std::thread

创建一个函数

void incrementThread(int &i)
{
  while(someCondition)
  {
    //sleep for 10 seconds
    //increment your value
    i++;
    std::this_thread::sleep_for(std::chrono::duration<int>(10));
  }
}

现在从 main 开始:

int main()
{
  int i = 0;
  std::thread t(incrementThread, std::ref(i));
  t.detach() // or t.join()
}

关于C++ - 不断递增一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30665958/

相关文章:

c++ - "const char*"类型的参数与 "char*"类型的参数不兼容。但为什么? :(

c - 为什么这些构造使用增量前和增量后未定义的行为?

C - 在 C 8051 中递增 18 位

c++ - 从 char(不是 char*)到 std::string 的首选转换

c++ - 将指针转换为不同类型的 vector

c++ - 重置对象

c - Arduino增量运算符不影响变量吗?

c++ - 实现混合插入和快速排序C++

c++ - C++ 预处理器中的前缀增量

performance - x86 inc 与 add 指令的相对性能