如果函式不修改非本地資料,我認為它們是執行緒安全的。
根據這個答案,我的假設是正確的。但是,最近我遇到了這段代碼,
int intRand(const int & min, const int & max) {
static thread_local std::mt19937 generator;
std::uniform_int_distribution<int> distribution(min,max);
return distribution(generator);
}
代碼讓我很困惑。thread_local如果函式已經是執行緒安全的,為什么要使用它?
uj5u.com熱心網友回復:
標準庫的亂數生成器(包括std::mt19937示例中使用的)不能在多執行緒中無序使用。thread_local保證每個執行緒都有自己的生成器,這使得可以從多個執行緒中呼叫未排序的函式。
如果函式不修改非本地資料,我認為它們是執行緒安全的。
靜態存盤是非本地的。即使具有靜態存盤持續時間的變數是區域變數,也是如此。名字是本地的;存盤是全域的。
uj5u.com熱心網友回復:
這只是為了清楚起見。
static thread_local std::mt19937 generator;
和
thread_local std::mt19937 generator;
是一樣的東西。
該static是在這種情況下化妝品。兩者都是static。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/341805.html
標籤:C
下一篇:C 組合列舉映射
