C ++如何判断一个互斥体是否在阻塞其他线程的同时被单个线程过度占用

我想分析特定的互斥锁如何在两个线程之间分时共享。我正在尝试调试一个问题,使我感到其中一个线程正在非常快速地锁定/解锁,这可能会使另一个线程因获取该锁而挨饿。

详细信息:

线程T1:

./usrMenu/add/add.sh "$2" # Let "$2" in this script become "$1" in add.sh

线程T2:

while (1) {
  //...non-blocking trivial work

  lock();
  //do little work on a shared DS1
  unlock();

  //...blocking work
}

线程T1是调度程序线程,它非常频繁地执行紧密循环检查,是否已更新共享DS1。 线程T2完成了更多工作,并最终更新了共享的DS1。

我觉得T1严重占用了锁,而T2却因为无法足够快地获取锁而使T2饿了。

我想测量特定线程在该锁上保留的时间。 T2在争用锁上花费了多少时间。

yanhua0801 回答:C ++如何判断一个互斥体是否在阻塞其他线程的同时被单个线程过度占用

测量T2等待lock()调用返回所花费的时间应该很简单:

// Thread T2
run() {
   //...does a bunch of blocking work

   // use whatever get-current-time API you like here
   const uint64_t t1 = get_current_time_in_microseconds();  
   lock();
   const uint64_t t2 = get_current_time_in_microseconds();

   const uint64_t time_spent_waiting_for_lock = (t2-t1);

   // Add code here to calculate minimum/average/max values 
   // of time_spent_waiting_for_lock over the course of your test

   // update shared DS1
   unlock();

   return;
}
本文链接:https://www.f2er.com/3140841.html

大家都在问