Microsoft MVP성태의 닷넷 이야기
닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [링크 복사], [링크+제목 복사],
조회: 4042
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - .NET 7부터 추가된 Int128, UInt128

(gcc 등에서는 지원하지만) Visual C++도 지원하지 않는 Int128을 닷넷 8부터 추가해 C# 언어에서도 사용할 수 있게 되었습니다. ^^

Int128 Struct
; https://learn.microsoft.com/en-us/dotnet/api/system.int128

단지, 다른 타입과는 달리 C# 측에서 대응하는 alias가 없어 BigInteger를 사용하듯이 써야 합니다.

{
    Int128 value = long.MaxValue;
    value *= long.MaxValue;
    Console.WriteLine(value); // 85070591730234615847396907784232501249
}

{
    Int128 value = Int128.Parse("85070591730234615847396907784232501249");
    Console.WriteLine(value);
}

개인적으로 이걸 보고 궁금했던 게, Interlocked 측에서의 지원이 있느냐는 것이었습니다. 아쉽게도 여전히 (8바이트) long 형식까지만 지원하지만, 그래도 아예 불가능한 것은 아닙니다. 만들면 되니까요? ^^




이를 위해 우리는 inline asm 기법을 사용해야 합니다.

C++의 inline asm 사용을 .NET으로 포팅하는 방법
; https://www.sysnet.pe.kr/2/0/1267

게다가 InterlockedCompareExchange128 API를 구현한 소스 코드가 GitHub에 있으니,

Execute a InterlockedCompareExchange128 natively from C#
; https://gist.github.com/jduncanator/ab17e4e476300d3eb0b7c19f6f38429a

기왕이면 여기에 함수 포인터를 곁들여,

C# 9.0 - (6) 함수 포인터(Function pointers)
; https://www.sysnet.pe.kr/2/0/12374

다음과 같은 식으로,

using System.Runtime.InteropServices;

namespace int128sample;
public unsafe class InterlockedExtension
{   
    // Execute a InterlockedCompareExchange128 natively from C#
    // ; https://gist.github.com/jduncanator/ab17e4e476300d3eb0b7c19f6f38429a
    static byte[] asmCmpXchg16b = new byte[] {
                0x48, 0x89, 0x5C, 0x24, 0x08,  // MOV [RSP+0x8], RBX
                0x49, 0x8B, 0x01,              // MOV RAX, [R9]
                0x49, 0x89, 0xCA,              // MOV R10, RCX
                0x48, 0x89, 0xD1,              // MOV RCX, RDX
                0x4C, 0x89, 0xC3,              // MOV RBX, R8
                0x49, 0x8B, 0x51, 0x08,        // MOV RDX, [R9+0x8]
                0xF0, 0x49, 0x0F, 0xC7, 0x0A,  // LOCK CMPXCHG16B [R10]
                0x48, 0x8B, 0x5C, 0x24, 0x08,  // MOV RBX, [RSP+0x8]
                0x49, 0x89, 0x01,              // MOV [R9], RAX
                0x0F, 0x94, 0xC0,              // SETE AL
                0x49, 0x89, 0x51, 0x08,        // MOV [R9+0x8], RDX
                0xC2, 0x00, 0x00               // RET 0
            };

    public static delegate* unmanaged[Stdcall, SuppressGCTransition] _InterlockedCompareExchange128;
    static GCHandle _InterlockedCompareExchange128Handle;

    static InterlockedExtension()
    {
        _InterlockedCompareExchange128Handle = GCHandle.Alloc(asmCmpXchg16b, GCHandleType.Pinned);
        nint pData = (nint)_InterlockedCompareExchange128Handle.AddrOfPinnedObject().ToPointer();
        
        EnsureMemoryIsExecutable(pData, asmCmpXchg16b.Length);
        _InterlockedCompareExchange128 = (delegate* unmanaged[Stdcall, SuppressGCTransition])pData;
    }

    // ...[생략]...
}

기반을 만들 수 있습니다. 간단하게 테스트 코드는 이렇게 만들 수 있고!

{
    Int128 value = 0;
    Int128 comparand = 0;
    InterlockedExtension._InterlockedCompareExchange128((long*)&value, 0, 1, (long*)&comparand);
    Console.WriteLine(value); // 출력 결과: 1
}




그런데 실행해 보면, 지난 글에서 다룬 것과 동일한 aligned 문제가,

Visual C++ - InterlockedCompareExchange128 사용 방법
; https://www.sysnet.pe.kr/2/0/13472#align16

GC Heap 또는 스택에 할당된 Int128 변수에 적용되므로 이런 예외가 확률적으로 발생하게 됩니다.

Fatal error. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at int128sample.Program.Main(System.String[])

만약 오류가 발생한다면 다음과 같이 변수 앞에 임시 조치를 취하면,

{
    long temporary = 0; // 8바이트 점유
    Int128 value = 0; // 이전에 8바이트 정렬이었다면 (운이 따르는 경우) temporary 변수로 인해 16바이트 위치로 변경
    // ...[생략]...
}

16바이트 정렬 효과를 갖게 돼 정상적으로 실행될 것입니다. 물론, 이 방법을 (release 빌드에서는 없어지는 문제도 있고, 최적화 시 재정렬될 수도 있으므로) 업무 코드에서 사용할 수는 없습니다. 그렇다면, C/C++의 경우 전역 변수를 사용하면 16바이트 정렬이 되었는데, C#은 어떨까요?

C#은 전역 변수라는 것이 없이, class 또는 struct 내에 static으로 흉내를 낼 수 있는데요,

internal unsafe class Program
{
    static Int128 g_value = 0;

    static void Main(string[] args)
    {
        fixed(Int128* ptr = &g_value)
        {
            Int128 value = 0;
            Int128 comparand = 0;
            InterlockedExtension._InterlockedCompareExchange128((long*)ptr, 0, 1, (long*)&comparand);
            Console.WriteLine(value);
        }
    }
}

이것 역시 확률적으로 crash가 발생합니다. 이유는, g_value가 GC Heap(HighFrequencyHeap)에 할당이 될 텐데 그런 경우 16바이트 정렬된 위치에 할당이 되리라는 것을 보장할 수 없기 때문입니다.

그렇다고 C#에 C/C++과 같은 "__declspec(align(16))"이 있는 것도 아니고... 난감하군요. ^^




자, 그렇다면 C#에서 해결해야 할 가장 큰 난제는 바로 정렬입니다. 이를 위해 StructLayout의 Pack이 있지만,

[StructLayout(LayoutKind.Sequential, Pack = 16)]
public struct Data
{
    byte __padding0; // (운에 따라) 이 위치가 0x0018이라면,
    public Int128 Value; // 이 위치는 16바이트를 건너 뛴 0x0028로 정렬
}

비록 alignment에 관여를 하긴 해도, 그것은 내부 멤버들의 정렬에 영향을 주는 것이기 때문에 애당초 저 구조체가 8바이트 정렬로 되는 것을 막을 수는 없습니다.

그렇다면 Win32 API를 interop 해야 할 것 같은데, 다행히 .NET 6부터 NativeMemory.AlignedAlloc이 제공되므로,

NativeMemory.AlignedAlloc(UIntPtr, UIntPtr) Method
; https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.nativememory.alignedalloc

이것을 감싸 다음과 같은 도우미 타입을 만들 수 있습니다.

public unsafe class NativeInt128 : IDisposable
{
    nint _value;

    public NativeInt128() : this(0)
    {
    }

    public NativeInt128(long value)
    {
        _value = (nint)NativeMemory.AlignedAlloc(16, 16);
        *(Int128*)_value = value;
    }

    public nint ValuePtr
    {
        get { return _value; }
    }

    public Int128 Value
    {
        get
        {
            return *(Int128*)_value;
        }
        set
        {
            *(Int128*)_value = value;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~NativeInt128()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_value == 0)
        {
            return;
        }

        NativeMemory.Free(_value.ToPointer());
        _value = 0;
    }
}

그런 다음, 이렇게 써야 그나마 안전하게 C#에서 Int128에 대한 InterlockedCompareExchange128 코드를 사용할 수 있습니다.

NativeInt128 data = new NativeInt128();
Int128 comparand = 0;
InterlockedExtension._InterlockedCompareExchange128((long*)data.ValuePtr, 0, 1, (long*)&comparand);

자, 여기까지 모두 준비되었으면 이제 InterlockedCompareExchange128을 이용해 Interlocked Increment 기능도 구현할 수 있습니다.

public void InterlockedIncrement()
{
    Int128 comparand = *(Int128*)_value;
    long* ptrLow;
    long* ptrHigh;

    Int128 newValue;
    ptrLow = (long*)&newValue;
    ptrHigh = ptrLow + 1;

    do
    {
        newValue = comparand + 1;
    } while (InterlockedExtension._InterlockedCompareExchange128((long*)_value,
                    *ptrHigh, *ptrLow, (long*)&comparand) == 0);
}

결국 이렇게 해서 구현하긴 했지만, 사실 이 과정을 그냥 하나의 응용 사례라고만 보시고 실제 코드는 단순히 lock을 쓰는 것이 훨씬 더 효율적입니다. ^^

object _lockValue = new object();

public void InterlockedIncrement()
{
    lock (_lockValue)
    {
        this.Value ++;
    }
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, System.Text.Json에서의 Int128 직렬화는 .NET 8부터 추가되었다고 합니다.

Built-in support for Half, Int128 and UInt128 numeric types
; https://devblogs.microsoft.com/dotnet/announcing-dotnet-8-preview-7/#built-in-support-for-half-int128-and-uint128-numeric-types




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/25/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2023-12-31 02시08분
NativeMemory.AlignedAlloc은 내부적으로 (윈도우의 경우) aligned_malloc을 호출합니다.

_aligned_malloc
; https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/aligned-malloc

참고로 Virtual 메모리 수준에서 메모리 정렬을 요구하는 함수도 있습니다.

How to allocate address space with a custom alignment or in a custom address region
; https://devblogs.microsoft.com/oldnewthing/20231229-00/?p=109204

VirtualAlloc2 function (memoryapi.h)
; https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc2
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13697정성태7/26/2024386닷넷: 2283. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/2024297오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/2024328닷넷: 2282. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/2024306닷넷: 2281. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/2024460개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/2024471디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/2024525디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/2024534오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/2024528디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/2024664닷넷: 2280. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/2024675닷넷: 2279. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
13686정성태7/19/2024629오류 유형: 918. Visual Studio - ATL Simple Object 추가 시 error C2065: 'IDR_...': undeclared identifier
13685정성태7/19/2024701스크립트: 66. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법 - 두 번째 이야기
13684정성태7/19/2024867닷넷: 2278. C# - 문자열 보간식 사례
13683정성태7/18/2024890오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상
13682정성태7/18/2024953닷넷: 2277. WPF - 스레드에 종속되는 DependencyObject파일 다운로드1
13681정성태7/17/20241017닷넷: 2276. C# 13 - (2) 메서드 그룹의 자연 타입 개선 (메서드 추론 개선)파일 다운로드1
13680정성태7/16/20241031닷넷: 2275. C# - Method Group, Natural Type, function_type파일 다운로드1
13679정성태7/16/20241042Linux: 75. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크
13678정성태7/15/2024898VS.NET IDE: 191. Visual Studio 2022 - .NET 5 프로젝트를 Docker Support로 실행했을 때 오류
13677정성태7/15/20241032오류 유형: 916. MSBuild - CheckEolTargetFramework (warning NETSDK1138)
13676정성태7/14/2024996Linux: 75. gdb에서 glibc의 함수에 Breakpoint 걸기
13675정성태7/13/2024990C/C++: 166. C/C++ - DLL에서 template 함수를 export하는 방법파일 다운로드1
13674정성태7/13/20241043오류 유형: 915. Unhandled Exception: Microsoft.Diagnostics.NETCore.Client.ServerNotAvailableException: Unable to connect to Process
13673정성태7/11/20241065닷넷: 2274. C# 13 - (1) 신규 이스케이프 시퀀스 '\e'파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...