Skip to content

Commit

Permalink
Refactor memory allocation function, replace macro with SwooleG.std_a…
Browse files Browse the repository at this point in the history
…llocator
  • Loading branch information
matyhtf committed Nov 12, 2020
1 parent 79fd01f commit 531b7d3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 24 deletions.
24 changes: 4 additions & 20 deletions include/swoole.h
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ typedef unsigned long ulong_t;
#define SW_START_SLEEP usleep(100000) // sleep 1s,wait fork and pthread_create

/*-----------------------------------Memory------------------------------------*/
void *sw_malloc(size_t size);
void sw_free(void *ptr);
void *sw_calloc(size_t nmemb, size_t size);
void *sw_realloc(void *ptr, size_t size);

// Evaluates to the number of elements in 'array'
#define SW_ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
Expand All @@ -162,26 +166,6 @@ typedef unsigned long ulong_t;
#define SW_MEM_ALIGNED_SIZE(size) SW_MEM_ALIGNED_SIZE_EX(size, SW_DEFAULT_ALIGNMENT)
#define SW_MEM_ALIGNED_SIZE_EX(size, alignment) (((size) + ((alignment) -1LL)) & ~((alignment) -1LL))

#ifdef SW_USE_EMALLOC
#define sw_malloc emalloc
#define sw_free efree
#define sw_calloc ecalloc
#define sw_realloc erealloc
#else
#ifdef SW_USE_JEMALLOC
#include <jemalloc/jemalloc.h>
#define sw_malloc je_malloc
#define sw_free je_free
#define sw_calloc je_calloc
#define sw_realloc je_realloc
#else
#define sw_malloc malloc
#define sw_free free
#define sw_calloc calloc
#define sw_realloc realloc
#endif
#endif

/*-------------------------------Declare Struct--------------------------------*/
namespace swoole {
class MemoryPool;
Expand Down
24 changes: 20 additions & 4 deletions src/core/base.cc
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,22 @@ swoole::Logger *sw_logger() {
return g_logger_instance;
}

void *sw_malloc(size_t size) {
return SwooleG.std_allocator.malloc(size);
}

void sw_free(void *ptr) {
return SwooleG.std_allocator.free(ptr);
}

void *sw_calloc(size_t nmemb, size_t size) {
return SwooleG.std_allocator.calloc(nmemb, size);
}

void *sw_realloc(void *ptr, size_t size) {
return SwooleG.std_allocator.realloc(ptr, size);
}

void swoole_init(void) {
if (SwooleG.init) {
return;
Expand All @@ -109,10 +125,10 @@ void swoole_init(void) {
SwooleG.init = 1;
SwooleG.enable_coroutine = 1;

SwooleG.std_allocator.malloc = sw_malloc;
SwooleG.std_allocator.calloc = sw_calloc;
SwooleG.std_allocator.realloc = sw_realloc;
SwooleG.std_allocator.free = sw_free;
SwooleG.std_allocator.malloc = malloc;
SwooleG.std_allocator.calloc = calloc;
SwooleG.std_allocator.realloc = realloc;
SwooleG.std_allocator.free = free;

SwooleG.fatal_error = swoole_fatal_error;

Expand Down

0 comments on commit 531b7d3

Please sign in to comment.