简体   繁体   中英

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(). However, the read and write run simutaneously.

Is the usage of shared_lock and upgrade_lock wrong? 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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