利用__sync_bool_compare_and_swap(),实现无锁编程
CAS即compare and swap,每次都会和old 值进行比较,如果没有发生更改再用new值给ptr赋值,然后返回true
#include <bits/stdc++.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef __GNUC__
//#define ATOMIC
#define CAS
#define _ATOMIC_ADD_(x, y) __sync_fetch_and_add(x, y)
#define _ATOMIC_SUB_(x, y) __sync_fetch_and_sub(x, y)
#define _CAS_(ptr, old, new) __sync_bool_compare_and_swap(ptr, old, new)
#else
#define _ATOMIC_ADD_(x, y) ;
#define _ATOMIC_SUB_(x, y) ;
#define _CAS_(ptr, old, new) ;
#endif
int val = 0;
void* worker1(void* arg)
{
#ifdef ATOMIC
for (int i = 0; i < 50000; i++)
_ATOMIC_ADD_(&val, 1);
#endif
#ifdef CAS
int old = val;
int i = 0;
for (; i < 10000; i++) {
while (!_CAS_(&val, old, old + 1)) {
old = val;
}
}
printf("%d", i);
#endif
}
void* worker2(void* arg)
{
#ifdef ATOMIC
for (int i = 0; i < 50000; i++)
_ATOMIC_SUB_(&val, 1);
#endif
#ifdef CAS
int i = 0;
int old = val;
for (; i < 10000; i++) {
while (!_CAS_(&val, old, old - 1)) {
old = val;
}
}
printf("%d", i);
#endif
}
int main()
{
pthread_t tid[2];
pthread_create(&tid[0], NULL, worker1, NULL);
pthread_create(&tid[1], NULL, worker2, NULL);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
std::cout << val << std::endl;
return 0;
}