Preface
The story is originated from a "Translation" task. The work content is to rewrite the portal Java version automatically switch client to C ++ version. However, the initial phase of "Translation" is not smooth, because although the two languages have similar syntax, there are still some essential differences that are difficult to "literal translation ". Just as we always find it difficult to directly translate some words into Chinese counterparts when translating English articles, so we have to create a word or make a circle to explain it clearly. In addition, for a person who has been using Java for a long time and later switched to C ++ development, I can't keep away with the elegant Java thread model and all the variables (except the basic numeric variables) they are all referenced programming concepts, just new, silly memory management without delete, and practical static initialization blocks ......, I have been wondering why C ++ does not have built-in thread support, garbage collection, and other modern programming language features, similar to google's GO language. So during the development process, I have been searching for alternatives in the C ++ world that will bring me closer to Java habits when writing code. After a period of exploration and practice, I have summarized some experiences and examples, so that I can enjoy the simplicity and elegance of Java syntax functions without losing the powerful control and efficiency of C ++.
1. Thread model and lock
1.1 The Java thread model is supported at the language level. Generally, we can define a Thread using two methods: directly inheriting the Thread class and overwriting the run () method or implementing the Runnable interface and implementing the run () method. Run () Stores logic-related code. Call start () to start the thread. C ++ does not support thread models at the language level, but requires additional libraries to implement thread functions (such as pthread ). So you will be excited to see a bunch of functions such as pthread_create (), pthread_exit (), pthread_join (), and some more annoying attribute settings (pthread_attr_t ). Oh My God! And my concise thread model !!
God and the street cannot solve the problem. We can implement a java-like thread model by ourselves. First, define the interface IRunnable. The pure virtual function run () is used to implement the class filling logic.
The second step is to define the thread base class, which contains the familiar run () and start (). The custom Thread class only needs to inherit from AbstractThread and implement the run () method. As a result, the feeling of simplicity and freshness came back. However, if we want to inherit other classes from the custom Thread class, we need to use multiple inheritance. This is a part of C ++ that is prone to misuse and errors, pay special attention to subsequent code. Note that the mutex lock at the end of the Code should be used in each thread as the internal synchronization control of the thread, the synchronized keyword of java is actually implemented using the mutex lock in the base class Object. We need to write an additional one.
1.2 The lock Java language used a simple Synchronization Model before jdk1.5, that is, a mutex lock is defined in the base class objects in the Java World, therefore, all Java classes can use this lock for synchronization control. The specific operation is the member functions of the class modified with the synchronized keyword and the code block enclosed by {}. Therefore, the modified functions and code blocks can implicitly use the mutex lock of the Object for thread synchronization. The Epoch jdk1.5 introduced a separate thread package java. util. concurrent contains a variety of new thread models, thread security containers, locks, and other tools, greatly improving the availability of java thread tools.
Like the thread model, the C ++ language itself does not contain the lock function. We can implement the lock function only by using external libraries (such as pthread. It is still a bunch of annoying functions. We simply wrap it and hope to make it easier to use.
1.2.1 read/write lock
It was simply wrapped up, avoiding the pthread_XXX series of functions and some exceptions at the right time. It felt a lot easier to use at the time of login (or psychological effects ......).
1.2.2 mutex lock
Similar encapsulation ideas seem very high, but I always think there is something else that will make us feel overwhelmed. We will discuss it in the next section.
1.2.3 secure release of locks
Java has a very useful Exception Handling paradigm: try... Catch... Finally, java ensures that the code in the finally block will be executed no matter whether an exception is thrown in the try block. This gives us a chance to perform some regular cleanup actions after the exception occurs, such as shutting down database connections and Releasing locks. However, C ++ does not have a finally block, so if we add a lock to the function, once an exception occurs, we must make a lot of effort + fully implement the Code to ensure that the lock is safely released. How can we accomplish this arduous task more elegantly?
First, let's review a feature of C ++ Exception Handling: C ++ guarantees that when a function throws an exception, all the temporary variables declared before the exception throw point will be destructed. To use this property, we only need to wrap the code to be synchronized with {} and declare a lock Wrapper object (we define it as LockWrapper) at the beginning of the code block ), when the program executes this Code or throws an exception, the LockWrapper destructor will be called. At this time, we have the opportunity to release the lock in the destructor.
Therefore, we can write a mutex operation as follows. Concise, elegant, secure ......
1.3 atomic counters many times (such as generating protocol sequence) We all need a thread-safe counter, however, if a mutex lock is added before an int variable that is constantly ++ for thread security, it may be too heavy. However, if you do not add a mutex lock, it may cause a lot of troubles. Java. util. concurrent contains various types of thread-safe counters (AtomicInteger) and arrays (AtomicArray. C ++ is not so lucky. Some people once said that ++ I is an atomic operation on many platforms, but the actual test shows that this is not the case, so we can't be lazy, and we have to do it ourselves.
The basic idea is to use nested assembly to solve the problem, just like the synchronization method of the Linux kernel. The code is simple and should not need to be explained. The ++, --, and zeroing operations are all available. As a thread-safe counter, it is sufficient. Note that the 80x86 assembly is used, and this Code cannot be transplanted to other platforms. However, given that the company's servers are centrally deployed and configured from hardware to system, this problem should not be too worried.
2 reference and Memory Management
In the Java World, all the class variables except the basic numeric variables are referenced. The reference concept of Java is essentially different from that of C ++. the reference of C ++ refers to the alias of the variable. The reference in Java can be understood as the Wrapper of the pointer, it is thread-safe. In terms of memory management, we all know that the biggest selling point of Java is the garbage collection mechanism. With the continuous improvement of the garbage collection algorithm of virtual machines, garbage collection has little impact on system performance. People who have never used Java can think of it as new, no matter whether it is delete or pretty cool. At the same time, we don't have to worry about the memory leakage caused by the deletion of some resources, the memory will not be written down due to incorrect operations on the Raw pointer. Can we also have automatic memory management in C ++? The answer is boost: shared_ptr <T>.
2.1 shared_ptrshared_ptr is actually a wrapper with a Raw pointer. It manages the lifecycle of the resource in reference count mode. That is, when the shared_ptr is copied, the reference count of the resource object is increased by 1. When the shared_ptr object is parsed, the reference count of the resource object is reduced by 1, when the reference count is 0, shared_ptr will call the deleteer (direct delete pointer by default) to delete the specified resource object. So we can rest assured that the new object can be inserted into the shared_ptr, and then let the shared_ptr help us manage the resource object lifecycle. Since then, we don't have to worry about the problems caused by new forgetting to delete or throwing an exception before deleting, which greatly reduces the chance of Memory leakage in the program. This is exactly why the author of Objective C ++ has only the pointer to the boost library. Because it is so useful, we need to have a deeper understanding of its limitations and potential rules to avoid problems caused by misuse.
2.1.1 loop reference
In fact, reference counting is also the simplest garbage collection algorithm, but its major drawback is that there may be circular references. Once a circular reference is formed, the reference count of all resource objects on the ring will never be 0, and shared_ptr will not help us to correctly Delete resource objects that are useless, therefore, memory leakage occurs again. Fortunately, we can use weak_ptr to solve some problems. Let's look at the example below.
In this example, shared_from_this () is the shared_ptr used to obtain the this pointer. Consider parent _. If we change weak_ptr to shared_ptr, what will happen? Yes, the answer is circular reference. Weak_ptr is the observer of shared_ptr. When shared_ptr is assigned to weak_ptr, the reference count is not incremented by 1. Therefore, shared_ptr and weak_ptr can help us solve the problem of circular reference. However, it must be emphasized that we should first see the problems in the program similar to the above examples to solve the problem with shared_ptr and weak_ptr. But what if we don't see it? You still need to be careful ......
Java is more intelligent when dealing with a bunch of objects that are repeatedly referenced. The Garbage Collector will find some "objects" based on some algorithms ", then, find all the objects in use based on these objects. The remaining "Object islands" can be recycled. This avoids the problems caused by circular references. Of course, this is an out-of-the-box remark and has nothing to do with shared_ptr.
2.1.2 Mixed Raw pointer and shared_ptr Problems
As shown in the first example, a pointer is first added and then assigned to a shared_ptr variable in the bracket scope. After the scope ends, the shared_ptr destructor, the reference count is 0, and the memory pointed to by p is cleared, so the core will be dropped when p is used in the last row.
The second example is a little more complex, mainly because p4 deleted resources during the analysis. As a result, the pointer that has been parsed is deleted again after the analysis of p1 and p2, leading to an exception.
The conclusion here is that since shared_ptr is used, trust it and assign the resource object lifecycle management to it. We should no longer perform additional operations on the Raw pointer, neither getting it out nor assigning it to other shared_ptr. If this is the cause of the problem, it is not the shared_ptr error, but we actually misuse it.
2.1.3 obtain shared_ptr of this pointer from resource object
This pointer is a special pointer. Because shared_ptr is a non-intrusive (I don't know about google) management solution, the resource object itself has no idea about its reference count, therefore, if you want to obtain a shared_ptr pointing to your own in the resource object method, you need to perform some additional processing. As shown below, CResouce can use enable_shared_from_this: shared_from_this () in the member function to obtain the shared_ptr pointing to itself.
2.1.4 use temporary shared_ptr when the parameter causes problems
Consider the following code:
Void test ()
{
Foo (boost: shared_ptr <MyObj> (new MyObj (), g ());
}
Because C ++ does not guarantee the execution sequence of parameter expressions in the function, if the execution sequence in this example is new MyObj, g (), and shared_ptr, g () when an exception is thrown, MyObj will leak. Written in Objective C ++:
Void test ()
{
Boost: shared_ptr <implementation> sp (new MyObj ());
Foo (sp, g ());
}
2.1.5 shared_ptr and Polymorphism
Polymorphism is one of the three basic concepts of object-oriented. We can use polymorphism technology to achieve the separation of interfaces and implementations. Shared_ptr does not directly support polymorphism. For example, if there are Father and Child classes, Child inherits from Father. We cannot directly write it like this:
Shared_ptr <Father> p1 (new Father );
Shared_ptr <Child> p2 = p1; // compilation error.
To achieve the purpose of polymorphism, we must perform a display type conversion:
Shared_ptr <Father> p1 (new Father );
Shared_ptr <Child> p2 = static_pointer_cast <Child> (p1); // compilation error.
This is a costly conversion, but with flexibility.
2.1.6 execution efficiency
As we can imagine, since the reference count outside the resource object is used, synchronization is inevitable to ensure the accuracy of the reference count. Although the lock-free atomic Integer Operation is adopted in the new version to reduce the thread synchronization overhead to a certain extent, the overhead caused by the actual maintenance of the reference count in some stress testing accounts for about 5% of the CPU, there is no cost. If you really care about this 5%, you still need to find another solution.
2.1.7 auto_ptr and shared_ptr
Auto_ptr is the only pointer in stl. It does not use reference counting. It manages objects in the following way: if two auto_ptr values are assigned, the assignment party will "transfer" the control of the pointer to the assigned party. From the source code, the assignment party handed over the pointer to the assigned party, and then assigned a NULL internally. In this way, auto_ptr cannot be placed in the stl container. Taking vector <auto_ptr <T> as an example, if one of the values is assigned to an external auto_ptr, the control of the pointer is transferred, and the value in the vector becomes NULL, this can cause program crashes at any time. The author of Objective C ++ said: in this case, if the compiler reports an error, you are lucky. If no error is reported, you should be more careful.
2.2 NullPointer for shared_ptr in Java, if the reference is null, we can return NULL, which is the same as the null pointer in C ++. But if shared_ptr is empty, how should we express it? This is a common requirement. For example, we have a function that returns shared_ptr of resources in a cache. Sometimes we need to return a blank smart pointer to the user to indicate that there is no resource change in the cache. The default constructor can only generate a NULL value in the pointer. However, to make it clearer, I choose to do this:
Shared_ptr <MyObj> pNullInfo (static_cast <MyObj *> (0 ));
To determine whether pNullInfo is null, you only need to use it like the following, which is the same as the Raw pointer usage.
If (! PNullInfo)
......
Else ......
3 static initialization code block
A static code block can be defined in the Java class to perform some necessary initialization actions. Like this:
Class Foo {
Static {
...... // Some initialization actions
}
....... // Other operations
}
The code in the static block will be executed (lazy loading) when the class object is used for the first time, which is very convenient. However, C ++ does not support this method. According to the initialization method of C ++, it is difficult for us to perform more complex initialization actions on static members defined in the class. It is okay to simply assign an initial value. If it is complicated, there is no way. The general solution is to write a static init () method, and require the class users to call this init before using the class for necessary initialization. This method is both troublesome and insecure (locks are required in the case of multiple threads ).
One solution I came up with is to generate and write a nested class in the class and declare a static member of the class. The initialization action to be performed can be placed in the constructor of the nested class. Therefore, when the class is initialized, the corresponding action is also executed. C ++ ensures that all static members have been initialized before the class is used. So we can get the same effect as the static code block in java. Write an example as follows:
4 references:
1. shared_ptr four sins http://blog.liancheng.info /? P = 85
2. About boost: shared_ptr... happy too early http://www.cppblog.com/Charlib/archive/2010/02/22/76313.html
This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/kabini/archive/2010/12/05/6056613.aspx