【发布时间】:2018-04-05 07:32:41
【问题描述】:
类成员函数将在其critical section 或critical data 上使用mutex 和lock_guard。我可以看到这可以通过两种不同的方式完成。
案例 1: - 在 for 循环内部。 lock_guard 在每次迭代时被构造和销毁。
std::mutex s_mutex;
class Foo {
public:
void bar() {
for ( ... ) {
std::lock_guard<std::mutex> guard( s_mutex );
// critical section data
} // lock_guard goes out of scope and releases or unlocks mutex
}
};
案例 2: - 在 for 循环之外。 lock_guard 创建一次,循环完成后销毁。
std::mutex s_mutex;
class Foo {
public:
void bar() {
std::lock_guard<std::mutex> guard( s_mutex );
for ( ... ) {
// data
}
} // lock_guard goes out of scope releasing or unlocking mutex.
};
我知道在第一种情况下,一个线程可以在一次迭代中访问循环,而不同的线程可以在不同的迭代中访问循环,但是没有两个线程可以同时访问临界区。至于第二种情况,我确实知道如果一个线程正在访问循环,那么第二个线程在完全完成之前无法触及该循环。
一种方法比另一种更可取还是取决于使用意图?两者之间是否存在性能影响?只是想对尝试维护现代 c++ 最佳实践进行一些澄清。
【问题讨论】:
标签: multithreading locking mutex c++17