簡體   English   中英

模板函數中的靜態std :: mutex不起作用

[英]Static std::mutex in templated function doesn't work

我有一個這樣的程序。

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;

template<int Thread>
void run()
{
    for(int j=0;j<5;++j)
    {
        static std::mutex m;
        m.lock();
        cout<<"Thread "<<Thread<<" running... "<<j<<endl;
        m.unlock();

        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

int main(int argc , char * argv [])
{
    std::thread t1(run<1>);
    std::thread t2(run<2>);

    t1.join();
    t2.join();

    return 0;
}

run()有一個靜態互斥量,以確保cout將以獨占方式執行。 但是,當我在Visual Studio 2012中運行該程序時,輸出為:

Thread Thread 2 running... 01
 running... 0
Thread 1 running... 1
Thread 2 running... 1
Thread 1 running... 2
Thread 2 running... 2
Thread 2 running... 3
Thread 1 running... 3
Thread 1 running... 4
Thread 2 running... 4

看起來互斥體無法正常run()的第一個循環。 我的程序有問題嗎?

您面臨的問題來自以下事實:您的函數是模板,而run<1>run<2>並不相同,並且它們不共享相同的靜態對象。

解決方案是將線程號作為參數傳遞給函數。

您應該放置以下行:

static std::mutex m;

run() 例如,在與run()相同的級別上全局聲明它。

由於您使用的是模板,因此構造了兩個不同的run()函數,每個函數都有自己的互斥量m ,互斥量m對彼此不可見。

在模板的每個實例中,您都有不同的互斥量。 您需要將互斥鎖設置為全局變量,否則必須安排在模板生成的每個函數中使用相同的互斥量。

這不是std :: mutex的問題。 您的run函數聲明兩個靜態互斥量,並為每個線程鎖定一個。

考慮在main聲明互斥量並將其作為參數傳遞給函數,在全局聲明它並將其鎖定在run函數中,或者將run函數設為非模板函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM