One is to use boost::atomic; a direct lock; The code is simple:
#include <boost/atomic/atomic.hpp> #include <iostream> #include <stdlib.h> #include <boost/ thread/mutex.hpp> #include <pthread.h> #include <stdio.h> #include <sys/time.h> #include < time.h> static int loop_num = 10000;boost::atomic<int> A (0); static Boost::mutex mtx_;static void* test_atomic ( void* AGR) {int num = * (int*) agr;struct timeval t_start,t_end; long cost_time = 0; Gettimeofday (&t_start, NULL); long s Tart = ((long) t_start.tv_sec) *1000+ (long) t_start.tv_usec/1000; while (num--) {++a;} Gettimeofday (&t_end, NULL); Long end = ((long) t_end.tv_sec) *1000+ (long) t_end.tv_usec/1000; Cost_time = End-start; Std::cout << "Loopnum:" << loop_num << "test_atomic cost" << cost_time << "ms\n"; return NU LL;} static int b = 0;static void* test_lock (void* AGR) {int num = * (int*) agr;struct timeval t_start,t_end; long cost_time = 0; Gettimeofday (&t_start, NULL); Long start = ((long) t_start.tv_sec) *1000+ (long) T_start. tv_usec/1000; while (num--) {{Boost::mutex::scoped_lock lock (mtx_); ++b;}} Gettimeofday (&t_end, NULL); Long end = ((long) t_end.tv_sec) *1000+ (long) t_end.tv_usec/1000; Cost_time = End-start; Std::cout << "Loopnum:" << loop_num << "test_lock cost" << cost_time << "ms\n"; return NULL ;} int main (int agrc, char** argv) {if (AGRC < 2) {std::cout << "please input num:" << Std::endl;return 0;} pthread_t main_tid;int num1 = atoi ((char*) argv[1]); int num2 = Atoi ((char*) argv[2]); if (num1 = = 0) {pthread_create (& Main_tid, NULL, &test_atomic, &num2); Create Thread Pthread_join (Main_tid, NULL);} Else{pthread_create (&main_tid, NULL, &test_lock, &num2);//Create Thread pthread_join (Main_tid, NULL);}}
The test results are as follows:
[email protected]:~/code$./test 0 1000
loopnum:10000 test_atomic Cost 0 ms
[Email protected]:~/code$./test 1 1000
Loopnum:10000test_lock Cost 0 ms
[Email protected]:~/code$./test 1 100000
Loopnum:10000test_lock Cost 9 ms
[email protected]:~/code$./test 0 100000
loopnum:10000 test_atomic cost 2 ms
As the number of loops increases, the gap becomes larger, and with the realization of the two, one is the critical block, one using the compare change technique, or even the internal implementation of the Assembly.
In my notebook The result is this, which also illustrates the problem.
Performance comparison of mutex and atomic under Linux