_ATOMIC_ADD_和_ATOMIC_SUB_是我实现的两个宏,分别对应__sync_fetch_and_add(x, y)        __sync_fetch_and_sub(x,y)

x需要传地址,y为要加/减的数,可以替代多线程mutex编程

#include <bits/stdc++.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

#ifdef __GNUC__
#define _ATOMIC_ADD_(x, y) __sync_fetch_and_add(x, y)
#define _ATOMIC_SUB_(x, y) __sync_fetch_and_sub(x, y)
#else
#define _ATOMIC_ADD_(x, y) ;
#define _ATOMIC_SUB_(x, y) ;
#endif
int val = 0;

void* worker1(void* arg)
{
    for (int i = 0; i < 50000; i++)
        _ATOMIC_ADD_(&val, 1);
}

void* worker2(void* arg)
{
    for (int i = 0; i < 50000; i++)
        _ATOMIC_SUB_(&val, 1);
}

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;
}