gpt4 book ai didi

c++ - 使用boost::upgrade_lock和shared_lock实现读/写线程安全

转载 作者:行者123 更新时间:2023-11-30 03:59:28 27 4
gpt4 key购买 nike

double x = 10;
boost::shared_mutex xSharedMutex;


void r() {
boost::shared_lock<boost::shared_mutex> lock(xSharedMutex);
for (int i = 0; i < 100; i++) {
cout << "**** READ **** " << x << endl;
usleep(200);
}
}

void w() {
boost::upgrade_lock<boost::shared_mutex> lock(xSharedMutex);
for (int i = 0; i < 100; i++) {
x = i + 12;
cout << "---- WRITE ---- " << x <<endl;
usleep(200);
}

}

int main() {
boost::thread t1(&r);
boost::thread t2(&w);

sleep(3);
}

由于在 w() 中添加了 upgrade_lock,因此我希望读取和写入将按顺序进行。但是,读取和写入同时运行。

shared_lock和upgrade_lock的用法有错吗?如何解决?谢谢。

最佳答案

您需要唯一的写作所有权:

boost::unique_lock<boost::shared_mutex> lock(xSharedMutex);
for (int i = 0; i < 100; i++) {
x = i + 12;
std::cout << "---- WRITE ---- " << x << std::endl;
usleep(200);
}

或者您可以临时升级该锁:

upgrade_lock<shared_mutex> lock(xSharedMutex);
for (int i = 0; i < 100; i++) {
{
upgrade_to_unique_lock<shared_mutex> write_lock(lock);
x = i + 12;
std::cout << "---- WRITE ---- " << x << std::endl;
}
usleep(200);
}

当然,这个程序中的输出会混杂在一起,因为控制台输出没有受到任何类型的锁定(这完全是 UB)

关于c++ - 使用boost::upgrade_lock和shared_lock实现读/写线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880135/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com