Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - Threading-Safe std:list C++

I am new to multi-threading and I am trying to simply make some std:lists thread-safe. Would it be enough to do mutex.lock() and mutex.unlock() whenever an item is being added or removed to the lists? Again, I am only trying to make them thread-safe.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You must protect all access to the list in order to be safe. While reading from a list without a lock will not corrupt the list, if the list is modified while another thread is reading from it, either thread could become corrupt (i.e. crash, or produce incorrect results).

You must hold the lock for the entire span of code that you expect the contents to be stable for. If another thread can erase or reorder any element at any time, then this includes any time you have live iterators to its contents. If there are restrictions as to which threads can manipulate which elements, the locking requirements can be relaxed with respect to holding live iterators.

Using std::lock_guard can help make sure you manage the lock correctly. Just create an instance of it at the beginning of any scope that will manipulate your list, and at the end of the scope it will automatically unlock, even if the scope exits via exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...