【问题标题】:C++ - constantly increment an integerC++ - 不断增加一个整数
【发布时间】:2015-06-05 11:56:14
【问题描述】:

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

【问题讨论】:

  • 您正在搜索类似将在线程中独立于主程序执行的 10 秒后递增一个整数
  • 您不能通过存储开始时间并与当前时间进行比较,以算术方式按需完成相同的任务吗?
  • 您可以使用单独的线程。让它循环“每 10 秒左右”,让它在每次增量之间休眠 10 秒。但是你为什么要这个,你打算用这个值做什么?
  • 在开始时初始化一个base = getCurrentMillis。每当您想访问此整数时,请改用(getCurrentMillis - base) / (10 * 1000)。查找文档以找到getCurrentMillis

标签: c++ increment


【解决方案1】:

为此使用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()
}

【讨论】:

  • 这将增加存储在incrementThread中的i的本地副本,main中的i不会改变。
  • make i static 来解决这个问题(我认为)
  • 这不是线程保存。 i 必须被锁定或atomic&lt;int&gt;。否则来自不同线程的读/写访问是数据竞争和未定义的行为。
【解决方案2】:

使用C++11风格:

#include <atomic>
#include <iostream>
#include <thread>

int main()
{
    std::atomic<int> i{0};
    std::thread thread_time([&]() { while (true) { ++i; std::this_thread::sleep_for(std::chrono::seconds(10)); } });
    while (true) {
        std::cout << i.load() << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }
    thread_time.join();
    return 0;
}

【讨论】:

    猜你喜欢
    • 2011-03-07
    • 1970-01-01
    • 2012-04-21
    • 2011-04-18
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多