C++併發編程(CH04)[clock-03]

Waiting with a time limit

兩種等待時間,一種時等待多長時間然後返回,一種是等待到某這個時刻返回,std::condition_variable有對他們各有兩種實現支持.

Clocks

clock是一個class.它提供以下四種信息.

  1. The time now

    std::chrono::system_clock::now()
    
  2. The type of the value used to represent the times obtained from the
    clock

  3. the tick period of the clock
    時鐘頻率的表示方式std::ratio<1,25>表示每秒鐘tick
    25次.而std::ratio<5,2>表示2.5秒鐘tick一次.

  4. Whether or not the clock ticks at a uniform rate and is thus
    considered to be a steady clock 穩定的時鐘非常重要.
    std::chrono::steady_clock.

Durations

  1. 定義時間間隔

    chrono::duration<short, ratio<60,1>> s(20); // 1個單位60s,而總共爲20分鐘的時間間隔.
    
  2. 從大單位時間可以轉換爲小單位事件,小的轉換爲大的不行.強制轉換會被截斷.

    std::chrono::milliseconds ms(54802);
    std::chrono::seconds s=
      std::chrono::duration_cast<std::chrono::seconds>(ms);
    //(sai:可以使用duration_cast進行時間轉換) nanoseconds, microseconds, milliseconds, seconds, minutes, and hours.可以用 
    

    There are also typedefs for all the SI ratios from std::atto
    (10–18) to std::exa (1018) (and beyond, if your platform has
    128-bit integer types) for use when specifying custom durations such
    as std::duration<double,std::centi> for a count of 1/100th of a
    second represented in a double .

  3. C++14的chrono_literals

    using namespace std::chrono_literals;
    auto one_day=24h;
    auto half_an_hour=30min;
    auto max_time_between_messages=30ms;
    
  4. 線程如何等待一段時間就返回.

    std::future<int> f=std::async(some_task);
    if(f.wait_for(std::chrono::milliseconds(35))==std::future_status::ready)
      do_something_with(f.get());
    //(如何等待線程一定時間)
    

    使用的是steady clock

Time points

auto start=std::chrono::high_resolution_clock::now();
do_something();
auto stop=std::chrono::high_resolution_clock::now();
std::cout<<"do_something() took "
   <<std::chrono::duration<double,std::chrono::seconds>(stop-start).count()
   <<" seconds"<<std::endl;
//一個時間點加上一個時間duration時下一個時間點,兩個時間點相減時一個時間duration

條件變量等待直至某個時刻到來.

#include <condition_variable>
#include <mutex>
#include <chrono>

std::condition_variable cv;
bool done;
std::mutex m;

bool wait_loop()
{
  auto const timeout= std::chrono::steady_clock::now()+
    std::chrono::milliseconds(500);
  std::unique_lock<std::mutex> lk(m);
  while(!done)
    {
      if(cv.wait_until(lk,timeout)==std::cv_status::timeout)
        break;
    }
  return done;
  //使用timeout對條件變量進行等待
}

注意上面的線程,比每次if語句都等待一段時間要好.因爲到了某個節點之後,就break.如果是每次都等待一段時間.如果繁忙while循環會一直運行下去.

Functions that accept timeouts

std::this_thread::sleep_for()
std::this_thread::sleep_until()

std::timed_mutex
std::recursive_timed_mutex
//try_lock_for() 
//try_lock_until()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章