2015-03-03 35 views
0

我在一個多線程程序中使用libcurl和OpenSSL。基於從是Daniel Stenberg發明的一種反應和例子多線程OpenSSL

我嘗試下面的代碼:

static std::mutex* aMutex; 

void locking_function(int mode, int n, const char* file, int line) 
{ 
    if(mode & CRYPTO_LOCK){ 
     std::cout << "Mutex locking\n"; 
     aMutex[n].lock(); 
    } 
    else{ 
     std::cout << "Mutex unlocking\n"; 
     aMutex[n].unlock(); 
    } 
} 

unsigned long id_function() 
{ 
    return (unsigned long)std::hash<std::thread::id>() (std::this_thread::get_id()); 
} 

int thread_setup() 
{ 
    aMutex = new std::mutex[CRYPTO_num_locks()]; 
    if(!aMutex) 
     return 0; 
    else{ 
     CRYPTO_set_id_callback(id_function); 
     CRYPTO_set_locking_callback(locking_function); 
    } 
    return 1; 
} 

int thread_cleanup() 
{ 
    if(!aMutex) 
     return 0; 

    CRYPTO_set_id_callback(NULL); 
    CRYPTO_set_locking_callback(NULL); 
    delete[] aMutex; 
    aMutex = NULL; 
    return 1; 
} 

所以我提供了鎖定函數,線程標識符函數和讓locking_function使用全局互斥量數組。

句子「互斥鎖定」和「互斥鎖解鎖」(打印在locking_function中)反覆打印得非常快。當我銷燬CURL手柄時,它會停下來。這是正常的還是正確的?

我打電話

thread_setup 

我的應用程序啓動並

thread_cleanup 
應用程序結束時

時。

感謝您的任何幫助。

回答

0
The sentences "Mutex locking" and "Mutex unlocking" (which are printed in the locking_function) gets printed over and over really fast. 

互斥鎖定/解鎖使用,以確保只有一個線程訪問臨界區在同一時間(這就是爲什麼它被稱爲互斥)。在多線程程序中,使用互斥數組並使用相同的方法來鎖定/解鎖它們,這兩個我期望會被調用很多次。另外關鍵部分的執行通常很快(只需幾行代碼)。

所以給你一個直接的答案,是的,你看到的是正常

+0

謝謝!我對一般的互斥體和多線程有一個體面的把握,但對OpenSSL和libcurl的經驗很少,所以並不知道OpenSSL會有什麼樣的行爲。 – jensa 2015-03-03 09:54:18

0

請注意,在有些平臺上的代碼可能有一個錯誤:

(unsigned long)std::hash<std::thread::id>() (std::this_thread::get_id()); 

std::hash()回報size_t你投它到unsigned long。在Win-64平臺上,size_t是64位,而unsigned long是32位。

+0

甚至更​​多 - std :: hassh不保證沒有碰撞 - 它可能爲兩個不同的'thread_id'值返回相同的值,可能會導致UB。 – 2018-01-12 02:20:58