Roger World
Roger World

Reputation: 301

Synchronization between threads

I'm a student and I want to understand synchronization between threads.

I have two threads t1 and t2.

I have a shared piece of memory between them.

/*e.g.*/ std::map<std::string, std::string> data;

One thread let's say t1 is reading data, and the other is writing..

std::mutex mu; //is used for synchronization

std::string read_1(std::string key)
{
    return data[key];
}

std::string read_2(std::string key)
{
    mu.lock();
    return data[key];
    mu.unlock();
}

void write(std::string key, std::string value)
{
    mu.lock();
    data[key] = value;
    mu.unlock();
}

read_1 is it thread safe?

if not what's the best way to optimize this code?

thanks.

Upvotes: 0

Views: 93

Answers (2)

Jesper Juhl
Jesper Juhl

Reputation: 31465

No. read_1 is not thread safe. It needs to lock the mutex before accessing data.

This would be safe;

std::string read_1(std::string key)
{
    std::lock_guard<std::mutex> guard(mu);
    return data[key];
}

Also; your read_2 function is broken. It returns before unlocking the mutex. If you had used a std::lock_guard then you wouldn't have had that problem.

Upvotes: 1

Paul Evans
Paul Evans

Reputation: 27577

read_1 is it thread safe?

No, it's reading when there could be a write to that data.

if not what's the best way to optimize this code?

Use a std::shared_mutex perhaps.

Upvotes: 1

Related Questions