C++ std::atomic은 lockfree일까?

이용준·2023년 3월 11일
0
post-thumbnail

개발 환경

Visual Studio 2022, MSVC, C++17, Windows 10

std::atomic은 원자적 연산을 제공한다.
atomic 클래스는 is_lock_free() 함수를 통해 락 여부를 알 수 있는데 실행 플랫폼과 타입크기에 따라 락을 걸수도, 안걸수도 있다.

테스트

4개의 구조체를 정의한다.

struct doubleInt8
{
    int8 v1, v2;
};
  
struct doubleInt16
{
  	int16 v1, v2;
};
  
struct doubleInt32
{
	int32 v1, v2;
};
  
struct doubleInt64
{
  	int64 v1, v2;
};

각 타입들이 atomic클래스를 사용할 때 is_lock_free() 결과를 확인해보자.

atomic<int8> aint8;
cout << "int8 size: " << sizeof(aint8) << "bytes. islockfree? " << aint8.is_lock_free() << endl;
// output : int8 size: 1bytes. islockfree? 1

atomic<int16> aint16;
cout << "int16 size: " << sizeof(aint16) << "bytes. islockfree? " << aint16.is_lock_free() << endl;
// output : int16 size: 2bytes. islockfree? 1
 
atomic<int32> aint32;
cout << "int32 size: " << sizeof(aint32) << "bytes. islockfree? " << aint32.is_lock_free() << endl;
// output : int32 size: 4bytes. islockfree? 1
  
atomic<int64> aint64;
cout << "int64 size: " << sizeof(aint64) << "bytes. islockfree? " << aint64.is_lock_free() << endl;
// output : int64 size: 8bytes. islockfree? 1
  
atomic<doubleInt8> adint8;
cout << "doubleInt8 size: " << sizeof(adint8) << "bytes. islockfree? " << adint8.is_lock_free() << endl;
// output : doubleInt8 size: 2bytes. islockfree? 1
  
atomic<doubleInt16> adint16;
cout << "doubleInt16 size: " << sizeof(adint16) << "bytes. islockfree? " << adint16.is_lock_free() << endl;
// output : doubleInt16 size: 4bytes. islockfree? 1
  
atomic<doubleInt32> adint32;
cout << "doubleInt32 size: " << sizeof(adint32) << "bytes. islockfree? " << adint32.is_lock_free() << endl;
// output : doubleInt32 size: 8bytes. islockfree? 1
  
atomic<doubleInt64> adint64;
cout << "doubleInt64 size: " << sizeof(adint64) << "bytes. islockfree? " << adint64.is_lock_free() << endl;
// output : doubleInt64 size: 24bytes. islockfree? 0

마지막줄의 doubleInt64 구조체의 크기는 16바이트지만, lockfree 연산을 지원하지않아 내부의 락을 잡기위한 8바이트 공간이 추가되어 24바이트로 확인되는 것을 알 수 있다.

일반적인 개발환경에서는 8바이트 이하에서 lockfree를 지원하지만 하드웨어 지원여부에 따라 달라진다.
std::atomic 문서

profile
소프트웨어 개발, 유니티, 게임 서버

0개의 댓글