Thread-Safe Initialization of Data
The story is simple if the data is not modified when shared between threads. The data has only to be initialized in the thread-safe way. It is not necessary to use an expensive lock for each access.
This author has not written his bio yet.
But we are proud to say that Rainer Grimm contributed 595 entries already.
The story is simple if the data is not modified when shared between threads. The data has only to be initialized in the thread-safe way. It is not necessary to use an expensive lock for each access.
If the previous post showed something, it’s that you should use mutexes with great care. That’s why you should wrap them in a lock.
The usage of mutexes seems extremely simple. There is a critical section in the code that a single thread can only access at any point in time. It’s ensured by a mutex m. The calls m.lock() and m.unlock() guarantee this exclusivity. But the devil is in the details.
With C++14 came reader-writer locks. The idea is straightforward and promising. Arbitrary reading threads can access the critical region simultaneously, but only one thread is allowed to write.
I created a repository for the source code. It’s on GitHub and has the name ModernesCppSource:https://github.com/RainerGrimm/ModernesCppSource.git
One of the biggest challenges of thread management begins when the threads share non-const data
A thread gets its data by copy or by reference. By default, you should use by copy. Why? In case your thread gets its data by reference, you have to be extremely careful about the lifetime of the arguments.
The parent has to take care of their child. This simple idea has big consequences for a thread lifetime. The following program starts a thread that displays its ID.
After a lot of discussion with my proofreaders, we finally have a process to publish the articles.
Thread creation is easy. Call std::thread, and a new thread will be created. The thread gets a work package and starts it immediately. The creator of the thread (the Parent) has to take care of the created thread (the child). The parent should wait until their child completes their task or has to detach himself […]