When we write a concurrent program, we have various methods to guarantee our program is linearizable and serializable, which means different threads will write or read a area of same memory or variable sequentially. But the efficiency of these methods is very different. Next I will introduce four methods: atomic, spin lock, mutex and thread lock
, and compare these four methods to analysis which one is the fastest one (maybe is not the best one).
I use time ./exec
to estimate the running time of programs.
Atomic
|
|
Spin Lock
I use c++ atomic variable to implement a spin lock likely structure, because C++11
doesn’t provide a implementation of spin lock.
|
|
Mutex
I use c++11
mutex, not the mutex in unix
API, to doing test.
|
|
thread lock
There is not existing a thread lock method in C++11, so I use pthread_mutex_lock
and pthread_mutex_unlock
in pthread lib to instead. But thread library in C++11 is based on pthread, so I think this is a equally and right testing.
|
|
evaluation
I use two
threads in one process, and every thread do 10M times of increment operations.
methods | time |
---|---|
without any lock | 0.24s |
atomic | 1.08s |
spin lock | 2.90s |
mutex | 5.82s |
thread lock | 6.81s |
In a nutshell, making variable becoming atomic is the fastest one.
This is the link of all codes.