Because c++ does not provide thread-safe container out-of-the-box, I am trying to create a generic thread-safe container.
In a multithreaded environment, many threads may modify my list (or any other container). I want to ensure that my list is thread-safe and only a single thread can modify my list at any given time.
My code is below. I'd like to know if it would work in a
template<typename T>
class ThreadSafeContainer {
public:
ThreadSafeContainer(): lck{mtx}{};
T getContainer(){
return container;
}
private:
T container;
std::lock_guard<std::mutex> lck;
std::mutex mtx;
};
int main(){
ThreadSafeContainer<std::list<int>> list;
std::list<int> my_list = list.getContainer();
// multiple threads can access my_list in a thread-safe way
return 0;
}