我可能真的很老套,但我說只是測試你的代碼並自己測量它。例如,將以下代碼(臨時)添加到程序中,然後執行搜索並替換以將所有程序的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互斥體。 –