简体   繁体   English

检测C Pthread中的等待线程

[英]Detect waiting threads in C Pthread

I have a thread pool with about 100 threads. 我有一个大约100个线程的线程池。 During testing, when I introduce some anomalous conditions, the overall process becomes very slow. 在测试期间,当我引入一些异常情况时,整个过程变得非常缓慢。 Once I make the things normal, the process becomes fast again. 一旦一切正常,该过程将再次变得快速。 Therefore, all threads are running. 因此,所有线程都在运行。

I want to detect which threads get slow in particular. 我想检测哪些线程特别慢。 For this, I want to write another thread whose responsibility will be to keep an eye on other threads, and report periodically which of them is waiting for a resource to get released. 为此,我想编写另一个线程,负责监视其他线程,并定期报告它们中的哪个正在等待资源被释放。 Is there a way (in Pthread) I can find which threads are waiting for some resource to get released, ie which threads are "hung" -- if it is a right term to use? 有没有一种方法(在Pthread中),我可以找到哪些线程正在等待释放某些资源,即哪些线程已“挂起”-如果使用正确的话?

System: C, Pthread, Linux 系统:C,Pthread,Linux

PS: Please mention in comments if you need any other details. PS:如果您需要其他详细信息,请在评论中提及。

I'm probably really old-fashioned, but I say just instrument your code and measure it yourself. 我可能确实是过时的,但是我说只是对您的代码进行检测并自己进行测量。 For example, add something like the following code (temporarily) to your program, and do a search-and-replace to change all your program's pthread_mutex_lock() calls to instrumented_pthread_mutex_lock(). 例如,(暂时)向您的程序中添加类似以下代码的内容,并执行搜索和替换操作以将程序的所有pthread_mutex_lock()调用更改为instrumented_pthread_mutex_lock()。

Then run your program with stdout redirected to a file. 然后在将stdout重定向到文件的情况下运行程序。 Afterwards, you can look in the file and see which threads were waiting a long time for which mutexes. 之后,您可以查看文件,查看哪些线程等待了很长时间的互斥锁。

(Note that the printf() calls will change the timing of your program somewhat, but for this purpose I don't think it will matter much) (请注意,printf()调用将在某种程度上改变程序的时序,但是为此,我认为这并不重要)

#include <stdio.h>
#include <unistd.h>
#include <sys/times.h>

static unsigned long long GetCurrentClockTimeMicroseconds()
{
   static clock_t _ticksPerSecond = 0;
   if (_ticksPerSecond <= 0) _ticksPerSecond = sysconf(_SC_CLK_TCK);

   struct tms junk; clock_t newTicks = (clock_t) times(&junk);
   return ((((unsigned long long)newTicks)*(1000000))/_ticksPerSecond);
}

int instrumented_pthread_mutex_lock(pthread_mutex_t * mtx)
{
   unsigned long long beforeTime = GetCurrentClockTimeMicroseconds();
   int ret = pthread_mutex_lock(mtx);
   unsigned long long afterTime = GetCurrentClockTimeMicroseconds();

   unsigned long long elapsedTime = (afterTime-beforeTime);
   if (elapsedTime > 1000)  // or whatever threshold you like; I'm using 1 millisecond here
   {
      printf("Thread %li took %llu microseconds to acquire mutex %p\n", (long int) pthread_self(), elapsedTime, mtx);
   }
   return ret;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM