Just finished the message server project, the project was developed in C + +, did not introduce the characteristics of C + + to smart pointers, bind/function and so on. At the time of development, the impression of one of the bugs is deep, the bug reason is that after the session object is released, continue to be used elsewhere.
Lock processing for critical resources. Shared objects for multiple threads by making the
1. Have experience in multi-threaded programming know that multithreaded programming is the most basic is through the lock to achieve the critical resources of the secure read and write.
Implementing a local lock
classmutexlock:boost::noncopyable{ Public: Mutexlock () {Pthread_mutex_init (&mutex_, NULL); } ~Mutexlock () {Pthread_mutex_destroy (&mutex_); } void Lock() {Pthread_mutex_lock (&mutex_); } voidunlock () {Pthread_mutex_unlock (&mutex_); } Private: pthread_mutex_t mutex_;};classmutexlockguard:boost::noncopyable{ Public: ExplicitMutexlockguard (mutexlock&mutex): Mutex_ (Mutex) {mutex_.Lock(); } ~Mutexlockguard () {mutex_.unlock (); } Private: Mutexlock&mutex_;}
2. Thread-Safe when constructing objects
(1) Do not register the callback function within the constructor function
(2) Do not pass this to the cross-threaded object in the constructor
(3) Even if the last line of the constructor is not possible, because if the class is a base class, the derived class is initialized after the base class is initialized.
Because the object has not been initialized during the execution of the constructor, this is passed to the cross-threaded object, and the object accesses a semi-finished product that may not have been initialized completely.
3. Object at the time of destruction
The resource is being used in a thread, but the B thread is freed. Causes a thread to access an invalid resource. The solution to this problem is to determine if the resource is valid before use. Using Tools weak_ptr and shared_ptr
SHARED_PTR itself is not thread-safe, multithreading security uses shared_ptr need to lock.
Shared_ptr will unexpectedly prolong the life of the object.
When the object is destroyed, the lock within the object does not work, and the lock is likely to be destroyed before it is used.
C + + multithreaded programming