From 6f3dc2afb13960d2298c779223685540793ea821 Mon Sep 17 00:00:00 2001 From: levlam Date: Thu, 18 Nov 2021 16:22:54 +0300 Subject: [PATCH] Use new/delete instead of ArrayAllocator on external threads. --- tdutils/td/utils/StackAllocator.cpp | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/tdutils/td/utils/StackAllocator.cpp b/tdutils/td/utils/StackAllocator.cpp index 37a406ba8..7a6d655d2 100644 --- a/tdutils/td/utils/StackAllocator.cpp +++ b/tdutils/td/utils/StackAllocator.cpp @@ -49,6 +49,19 @@ class ArrayAllocator final : public StackAllocator::AllocatorImpl { } } }; + +class NewAllocator final : public StackAllocator::AllocatorImpl { + MutableSlice allocate(size_t size) final { + return {new char[size], size}; + } + + void free_ptr(char *ptr, size_t size) final { + delete[] ptr; + } + + public: + ~NewAllocator() final = default; +}; } // namespace StackAllocator::Ptr::~Ptr() { @@ -58,9 +71,14 @@ StackAllocator::Ptr::~Ptr() { } StackAllocator::AllocatorImpl *StackAllocator::impl() { - static TD_THREAD_LOCAL ArrayAllocator *array_allocator; // static zero-initialized - init_thread_local(array_allocator); - return array_allocator; + if (get_thread_id() != 0) { + static TD_THREAD_LOCAL ArrayAllocator *array_allocator; // static zero-initialized + init_thread_local(array_allocator); + return array_allocator; + } else { + static NewAllocator new_allocator; + return &new_allocator; + } } } // namespace td