我正在學習如何在Boost庫使用線程,我的搜索過程中,我發現下面的代碼:void運算符()()瞭解
struct count
{
count(int id) : id(id) {}
void operator()()
{
for (int i = 0; i < 10; ++i)
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout << id << ": " << i << std::endl;
}
}
int id;
};
int main(int argc, char* argv[])
{
boost::thread thrd1(count(1));
boost::thread thrd2(count(2));
thrd1.join();
thrd2.join();
return 0;
}
這個程序工作正常,但我的問題是,什麼是void operator()()
函數的行爲?因爲有兩個線程,每個線程都使用不同的值初始化計數。這是兩個主要的count
變量是單獨創建的,所以他們的void operator()()
應該是不同的每個變量。但似乎void operator()()
是兩個線程相同。在這個代碼void operator()()
還有一件事是不是從任何地方被調用,所以它如何運行?
有人能解釋一下這個函數裏面發生了什麼嗎?
void operator()()
是什麼讓你覺得它們對於兩個線程都是一樣的? –
@JosephMansfield我運行這個程序檢查互斥鎖的工作情況,它顯示了互斥鎖的確切工作情況。它不允許其他線程在第一個線程完成之前處理此函數。 – nabeel