我有一个大约有100个线程的线程池。在测试期间,当我引入一些异常情况时,整个过程变得非常缓慢。一旦我把事情做好,这个过程就会变得很快。因此,所有线程都在运行。
我想检测哪些线程特别慢。为此,我想编写另一个线程,其职责是密切关注其他线程,并定期报告哪些线程正在等待资源被释放。有没有办法(在Pthread中)我可以找到哪些线程正在等待某些资源被释放,即哪些线程是"挂起" - 如果它是一个正确的术语?
系统:C,Pthread,Linux
PS:如果您需要任何其他细节,请在评论中提及。
答案 0 :(得分:2)
我可能真的很老套,但我说只是检测你的代码并自己测量它。例如,将以下代码(暂时)添加到程序中,并执行搜索和替换以将所有程序的pthread_mutex_lock()调用更改为instrumented_pthread_mutex_lock()。
然后使用重定向到文件的stdout运行程序。之后,您可以查看该文件,查看哪些线程长时间等待哪些互斥锁。
(请注意,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;
}