有一个新的实验功能(可能是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