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

时间:2014-11-12 05:48:24

标签: c++ multithreading boost 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);
}

由于w()中添加了upgrade_lock,我希望读取和写入顺序完成。但是,读写同时运行。

shared_lock和upgrade_lock的使用是否有误?怎么解决?感谢。

1 个答案:

答案 0 :(得分:2)

您需要独特的写作所有权:

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

或者你可以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);
}

当然,这个程序的输出混合在一起,因为控制台输出不受任何锁定(这是严格的UB)