Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Thread-Safe Object

This might seem like an incredibly simple question, but in all my research I haven't been able to find a clear example...

I'm trying to build a custom class with private variables accessible with getter and setter functions. This class will be instantiated once in the global scope (extern) and will serve as a data cache in my application. It will be used by many threads simultaneously, 99% for reading, and speed is extremely important. Is there any way to allow concurrent reads and just lock for writing? (I'm assuming not)

Do I simply include a scoped mutex as the first line of the getter and setter? Or how is the best way to design this seemingly simple object? Any examples or links would be greatly appreciated (I'm having a hard time wrapping my head around it).

I do have Boost compiled in, so it's usable.

I really appreciate it!

like image 685
Harry Avatar asked Mar 18 '14 22:03

Harry


People also ask

Is Objective C thread-safe?

It is unsafe for one thread to be reading an array while another thread appends to it.

What is a thread-safe object?

A thread-safe object is one that always maintains a valid state, as observed by other classes and objects, even in a multithreaded environment.

What does thread-safe mean C?

Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.

Are C functions thread-safe?

The stdio library is thread-safe if the _mutex_ * functions are implemented. Each individual stream is protected by a lock, so two threads can each open their own stdio stream and use it, without interfering with one another.


1 Answers

Assuming your encapsulation is correct, locks on the getter and setters should be sufficient.

To provide concurrent reads, look into Readers-Writer locks, which provides precisely the level of synchronization you desire. I think boost::shared_mutex fits the bill.

Since this is a cache, if you are able to tolerate out of date values, it may be worth it for you, in terms of performance, to investigate RCU, or Read-copy-update. There's at least one library for user-space RCU.

like image 161
Matthew G. Avatar answered Oct 15 '22 09:10

Matthew G.