Shaoyan
Shaoyan

Reputation: 117

Why shared_locked introduced before shared_mutex

In C++14 there is shared_lock as reader-writer lock. This you must use in conjunction with shared_mutex. Example:

// my shared data
std::shared_mutex mut;
Data data;

void process_data(const Data *); // read-only function
void update_data(Data *);

// multiple threads can read data
void read_data(){
    std::shared_lock lk(mut);
    process_data(&data);
}

// only one thread can read data
void write_data(){
    std::unique_lock lk(mut); // exclusive lock
    update_data(&data);
}

As long as I understand shared_mutex was introduced in C++17, later than shared_lock was introduced in C++14. You cannot use shared_lock without shared_mutex.

Why was shared_locked introduced in C++14 if there was no shared_mutex at that time?

Upvotes: 4

Views: 295

Answers (1)

Anthony Williams
Anthony Williams

Reputation: 68611

In C++14, there was std::shared_timed_mutex, which provides the same facilities as std::shared_mutex, with the addition of extra functions to support timeouts on the locks.

You could therefore use std::shared_lock with std::shared_timed_mutex just fine.

Initially it was believed that this was all that was required, but then implementors pointed out that they could make performance improvements by omitting the timeout functions, so std::shared_mutex was added as a separate type, but this was too late to add to C++14, so it was added to C++17.

Upvotes: 9

Related Questions