自己实现原子操作

#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#define ADD_CNT 10000
#define THREAD_NUM 10
pthread_t tids[THREAD_NUM];

int g_cnt = 0;

void printids(const char *s) {
  pid_t pid;
  pthread_t tid;

  pid = getpid();
  tid = pthread_self();
  printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid,
         (unsigned long)tid, (unsigned long)tid);
}

void *thr_fn(void *arg) {
  char buf[128];
  snprintf(buf, sizeof(buf), "new thread: index:%ld ", (int64_t)arg);
  printids(buf);

  for (int i = 0; i < ADD_CNT; ++i) {
    asm volatile("lock addq $1, %0" : "+m"(g_cnt));
  }

  return ((void *)0);
}

int main(void) {
  printf("begin g_cnt:%d \n", g_cnt);

  for (int i = 0; i < THREAD_NUM; ++i) {
    int err;
    int64_t i64 = i;
    err = pthread_create(&tids[i], NULL, thr_fn, (void *)i64);
    if (err != 0) {
      fprintf(stderr, "can't create thread, err:%d \n", err);
      exit(-1);
    }
  }

  printids("main thread:");
  for (int i = 0; i < THREAD_NUM; ++i) {
    pthread_join(tids[i], NULL);
  }

  printf("end g_cnt:%d \n", g_cnt);

  exit(0);
}