简体   繁体   中英

Standard cpp data structures and pthread mutex?

In one of the projects I am working on migration from C to C++. A lot of the C code uses pthread and mutex associated with this library for multithreading. I want to perform possibly step by step, incremental migration. I wanted to start with the data structures as they are most obvious but they would need to be synchronized using pthread mutex. Is usage of pthread mutex safe or only the standard library threading infrastructure (like std::mutex ) can guarantee proper memory interthread memory consistency?

Thread library in C++ provides higher level abstractions and other useful synchronization mechanisms, If your compiler supports C++11 or newever C++ standard features, In my opinion you should use C++11 thread library and experience beauty of RAII when managing shared resources.

I don't have much experience with pthreads, but pthread_mutex has same semantics as std::mutex and to answer your question

Is usage of pthread mutex safe or only the standard library threading infrastructure (like std::mutex ) can guarantee proper memory inter thread memory consistency

As I mentioned semantically they are same and you can build a locable abstraction (class with try_lock , unlock , lock methods) on top of pthread_mutex easily, it comes down to how you use both, for example

  • If you are causing data races or not
  • If you are using lock_guard , unique_lock or not, Because if you don't use RAII in addition to similar problems as in C for resource management, C++ statements can throw exception which will cause threads to deadlock if mutex is not unlocked.

Besides this there are bunch of other useful stuff available like std::recursive_mutex , std::shared_mutex , std::future s, std::promise s etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM