我可能真的很老套,但我说只是测试你的代码并自己测量它。例如,将以下代码(临时)添加到程序中,然后执行搜索并替换以将所有程序的pthread_mutex_lock()调用更改为instrumented_pthread_mutex_lock()。
然后用标准输出重定向到一个文件来运行你的程序。之后,您可以查看该文件,并查看哪些线程正在等待很长时间的哪些互斥锁。
(注意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;
}
大概不会,但你可能做到这一点你自己 - 在等待之前将一个标志设置为真,并在等待之后将其设置为假? – immibis
当你说“资源”时,你的意思是一个pthread锁/互斥锁或其他东西吗? –
@JeremyFriesner是的,当我说“资源”时,我的意思是一个pthread互斥体。 –