简体   繁体   English

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

[英]Using boost::upgrade_lock and shared_lock to implement read/write thread safety

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);
}

I expect that read and write will go sequentially because of an upgrade_lock has been added in w(). 我预计读写操作将按顺序进行,因为已在w()中添加了upgrade_lock。 However, the read and write run simutaneously. 但是,读取和写入同时进行。

Is the usage of shared_lock and upgrade_lock wrong? shared_lock和upgrade_lock的用法是否错误? How to fix it? 如何解决? Thanks. 谢谢。

You need either unique ownership for writing: 您需要拥有唯一的所有权才能编写:

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);
}

Or you can upgrade that lock ad-hoc: 或者,您可以临时升级该锁:

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);
}

Of course, the output in this program gets intermixed as the console output is not under any kind of lock (this is strictly UB) 当然,此程序的输出会混杂在一起,因为控制台输出不受任何锁定(严格来说是UB)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM