티스토리 뷰

개발/일상

c++ shared_ptr not thread-safe

clucle 2020. 6. 27. 18:09

Sample Error Code : 

https://wandbox.org/permlink/oAXbYnkKE5BR7Wig

 

[Wandbox]三へ( へ՞ਊ ՞)へ ハッハッ

 

wandbox.org

#include <iostream>
#include <memory>
#include <thread>

std::shared_ptr<int> g;

void read_g()
{
  std::shared_ptr<int> x;
  long sum = 0;
  for (int i = 0; i < 1000 * 1000; ++i)
  {
    x = g;
    sum += *x;
  }
  printf("sum = %ld\n", sum);
}
 
void write_g()
{
  for (int i = 0; i < 1000 * 1000; ++i)
  {
    auto n = std::make_shared<int>(42);
    g = n;
  }
}
 
int main()
{
  g = std::make_shared<int>(42);
  std::thread t1(read_g);
  std::thread t2(write_g);
  t1.join();
  t2.join();
}

Reference :

https://www.slideshare.net/zzapuno/multithread-sharedptr

 

Multithread & shared_ptr

How to avoid data race using shared_ptr

www.slideshare.net

assembly code

Shows an error when using shared_ptr in a multithreaded environment.

 

 

To solve this problem, atomically load and store shared_ptr.

 

Sample Correct Code : 

wandbox.org/permlink/OWNnFaPmXkbmdBAl

 

[Wandbox]三へ( へ՞ਊ ՞)へ ハッハッ

 

wandbox.org

#include <iostream>
#include <memory>
#include <thread>

std::shared_ptr<int> g;

void read_g()
{
  std::shared_ptr<int> x;
  long sum = 0;
  for (int i = 0; i < 1000 * 1000; ++i)
  {
    x = std::atomic_load(&g);
    sum += *x;
  }
  printf("sum = %ld\n", sum);
}
 
void write_g()
{
  for (int i = 0; i < 1000 * 1000; ++i)
  {
    auto n = std::make_shared<int>(42);
    std::atomic_store(&g, n);
  }
}
 
int main()
{
  g = std::make_shared<int>(42);
  std::thread t1(read_g);
  std::thread t2(write_g);
  t1.join();
  t2.join();
}

If there is a mistake, please contact me

댓글