shared_ptr 并发赋值,线程不安全

https://www.zhihu.com/question/56836057?sort=created

解决方法
c++11:
https://en.cppreference.com/w/cpp/memory/shared_ptr/atomic

c++20:
std::atomic<std::shared_ptr>

#include <cstdio>
#include <memory>
#include <thread>
#include <unistd.h>

static std::shared_ptr<int> g_pointer;

void foo(void) {
  int data = 0;
  for (;;) {
    auto p = g_pointer;
    if (p) {
      data += *p;
    }
  }
  printf("%d\n", data);
}

int main() {
  int i = 0;
  g_pointer = std::make_shared<int>(++i);
  std::thread t1(foo), t2(foo), t3(foo), t4(foo), t5(foo), t6(foo), t7(foo), t8(foo);
  for (;;) {
    usleep(10000);
    g_pointer = std::make_shared<int>(++i);
  }
  return 0;
}
posted @ 2020-07-09 16:57  stdpain  阅读(428)  评论(0编辑  收藏  举报