Elegantly enables a class to switch between thread safety and thread safety
Source: Internet
Author: User
A good multi-threaded library should not be fully locked. Sometimes, although it is a multi-threaded environment, a class may be operated by only one thread according to the design. In this case, locking is redundant, which is a waste of performance, however, in other scenarios, it is required to be thread-safe. Suppose there is a Class X: Class X {public: void Xoo () ;}; here we summarize several common practices: 1. the caller locks the lock itself, but the disadvantage is that if the lock is applied in most scenarios, repetition will occur. Code Class Z {public: void zoo () {lockhelper <clock> LH (_ Lock); // The caller Z locks _ x. xoo () ;}; PRIVATE: clock _ Lock; X _ x ;}; 2. in class implementation, add if to Judge Class X {public: X (bool is_threadsafe): _ is_threadsafe (is_threadsafe) {} void Xoo () {If (_ is_threadsafe) {// lock _ Lock Based on conditions. lock ();}...... If (_ is_threadsafe) {_ Lock. unlock () ;}} PRIVATE: bool _ is_threadsafe; clock _ Lock ;}; 3. it is divided into two classes. The first class is unlocked, the second class aggregates the first class, and uses the lock to wrap the class rawx {public: void Xoo () {// rawx always locks}; Class SAFEX {public: void Xoo () {lockhelper <clock> LH (_ Lock); // always locks _ raw_x.xoo ();} PRIVATE: clock _ Lock; rawx _ raw_x;}; The following describes a more elegant method used in mooon, which references an empty lock class cnulllock, it only provides the lock interface. The lock and unlock function bodies are empty: Class cnulllock {public: void lock () {} voi D unlock () {}}; next, let's look at the implementation of the new x. We need to convert it into a template class: Template <class lock> Class X {public: void Xoo () {lockhelper <clock> LH (_ Lock); // here it is not necessarily a lock}; if you need X to be thread-safe, you can use x <clock> X; if you do not need X to be thread-safe, you can use it as follows: x <cnulllock> X; does such an X seem more elegant?
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.