有一個新的實驗功能(可能是C++ 20),它是「同步塊」。該塊提供了一段代碼的全局鎖定。以下是cppreference的示例。C++中新功能「synchronized」塊的優點是什麼?
#include <iostream>
#include <vector>
#include <thread>
int f()
{
static int i = 0;
synchronized {
std::cout << i << " -> ";
++i;
std::cout << i << '\n';
return i;
}
}
int main()
{
std::vector<std::thread> v(10);
for(auto& t: v)
t = std::thread([]{ for(int n = 0; n < 10; ++n) f(); });
for(auto& t: v)
t.join();
}
我覺得這是多餘的。有沒有在synchronized塊之間從上面而這其中任何區別,:
std::mutex m;
int f()
{
static int i = 0;
std::lock_guard<std::mutex> lg(m);
std::cout << i << " -> ";
++i;
std::cout << i << '\n';
return i;
}
我發現這裏唯一的好處是,我得救了具有全局鎖的麻煩。使用同步塊有更多優點嗎?什麼時候應該首選?
不確定實際情況如何,但cppreference使它聽起來像第一個版本保證在第一個示例中按順序打印,而AFAIK第二個版本沒有。 – NathanOliver
@NathanOliver爲什麼不按順序打印第一個版本?你能解釋一下嗎?據我所知,整套代碼一次只能執行一次,包括打印,這將使一切順利進行。這也是互斥體的情況。 –
「雖然同步塊在全局鎖定下執行,但是實施需要檢查每個塊內的代碼,並針對事務安全的代碼使用樂觀併發(由可用的硬件事務內存備份)事務安全代碼「。 – cpplearner