C + + Atomic manipulation

Source: Internet
Author: User
Tags mutex

reprinted from: http: // blog.csdn.net/yockie/article/details/8838686
The so-called atomic operation, which is the meaning of the "atom is the smallest, indivisible minimum," means that when multiple threads access the same global resource, it is possible to ensure that all other threads do not access the same resources at the same time. That is, he ensured that only a single thread could access the resource at the same time. This is somewhat similar to the protection of the mutex object's access to the shared resource, but the atomic operation is closer to the bottom and thus more efficient. In the past CAtomic operations are not regulated in the + + standard, and we tend to use assembly language, or with third-party thread libraries, such as Intel's Pthread. In the new standard C + + One, introduced the concept of atomic operation, and through this new header file provides a variety of atomic operational data types, such as Atomic_bool,atomic_int, and so on, if we operate on these types of shared resources in multiple threads, the compiler will ensure that these operations are atomic, That is, to ensure that only one thread accesses the resource at any given time, the compiler guarantees that multiple threads will access the shared resource correctly. This avoids the use of locks and improves efficiency. Let's look at a practical example. If we want to design an ad click Statistics Program, in the server program, use multiple threads to simulate the clicks of multiple users on the ad: #include<boost/thread/thread.hpp>#include<atomic>#include<iostream>#include<time.h>using namespacestd;//Global Result DataLongTotal =0; //Click FunctionvoidClick () { for(intI=0; i<1000000;++i) {//Lock-free access to global dataTotal + =1; }}  intMainintargcChar*argv[]) {    //Timing Startsclock_t start =clock (); //Create 100 threads to simulate click StatisticsBoost::thread_group Threads;  for(intI=0; i< -;++i) {threads.create_thread (click);    } threads.join_all (); //End of timingclock_t finish =clock (); //Output Resultscout<<"Result:"<<total<<Endl; cout<<"Duration:"<<finish-start<<"Ms"<<Endl; return 0;} From the result of execution, such a method is very fast, but the result is not correct E:\SourceCode\MinGW>Thread.exeresult:87228026Duration:528ms Naturally, we would have thought of using mutexes to protect access to globally shared resources, so we had the following implementation:LongTotal =0;//mutex objects that are protected against shared resourcesMutex m;voidClick () { for(intI=0; i<1000000;++i) {//lock Mutex object before accessM.Lock(); Total+=1; //when the access is complete, release the mutex objectM.unlock (); }} The use of mutually exclusive objects, to ensure that only one thread at a time to access the share, from the execution of the results, mutually exclusive objects to ensure the correctness of the results, but also has a very large performance loss, from just 528ms into the present 8431, with the original time of 10 times. The loss is big enough. E:\SourceCode\MinGW>Thread.exeresult:100000000duration:8431ms If it's in C++11, our solution is over, but C + + 's quest for performance is endless, and he's always trying to squeeze the performance out of the CPU. In C + +11, the data type of atomic operation (Atomic_bool,atomic_int,atomic_long, etc.) is implemented, and the access to shared resources of these atomic data types can be achieved without the use of lock mechanism such as mutex, and the correct access to the share resource is realized. //introduce the header file of the atomic data type#include <atomic>//use atomic data types as data types for shared resourcesAtomic_long Total (0);//long total = 0; voidClick () { for(intI=0; i<1000000;++i) {//only the data type is different, and the form of access to it is no different from the resources of the ordinary data type.Total + =1; }} Let's look at the effect of using atomic data types: E:\SourceCode\MinGW>Thread.exeresult:100000000duration:2105ms results are correct! Time consuming is only one-fourth of mutex mutex objects used! It is only 4 times times as long as it does not take any protective mechanism. It can be said that this is a very good result. The implementation of atomic operations is similar to the normal data type, but it can provide better performance than the lock mechanism, such as mutex, if the shared resources we want to access can be represented by atomic data types, it is a good choice to use this new equivalent data type in multithreaded programs. 

C + + Atomic manipulation

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.