2016-07-27 66 views
0

我有一個線程池約100線程。在測試過程中,當我引入一些異常情況時,整個過程變得非常緩慢。一旦我把事情變得正常,這個過程又會變得很快。因此,所有的線程都在運行。檢測C中的等待線程Pthread

我想檢測哪些線程特別慢。爲此,我想編寫另一個線程,其職責是監視其他線程,並定期報告哪些線程正在等待資源釋放。有沒有一種方法(在Pthread中)我可以找到哪些線程正在等待某些資源被釋放,即哪些線程被「掛起」 - 如果它是一個正確的術語使用?

系統:C,Pthread的,Linux的

PS:請評論提到,如果您需要任何其他細節。

+0

大概不會,但你可能做到這一點你自己 - 在等待之前將一個標誌設置爲真,並在等待之後將其設置爲假? – immibis

+0

當你說「資源」時,你的意思是一個pthread鎖/互斥鎖或其他東西嗎? –

+0

@JeremyFriesner是的,當我說「資源」時,我的意思是一個pthread互斥體。 –

回答

2

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