Skip to content

Commit

Permalink
add CallOnce
Browse files Browse the repository at this point in the history
  • Loading branch information
quink-black committed Sep 8, 2024
1 parent 204583b commit 0ca79c8
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/platform.h.in
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@
#else
#include <pthread.h>
#endif
#if (__cplusplus >= 201103L) && !NCNN_SIMPLESTL
#include <mutex>
#endif
#endif // NCNN_THREADS

#if __ANDROID_API__ >= 26
Expand Down Expand Up @@ -141,6 +144,22 @@ public:
private:
DWORD key;
};

#if (__cplusplus < 201103L) || NCNN_SIMPLESTL
typedef INIT_ONCE OnceFlag;
#define OnceFlagInit INIT_ONCE_STATIC_INIT

static inline int CallOnce(OnceFlag &flag, void (*init_routine)(void))
{
BOOL pending = FALSE;
InitOnceBeginInitialize(&flag, 0, &pending, NULL);
if (pending)
init_routine();
InitOnceComplete(&flag, 0, NULL);
return 0;
}
#endif // < c++11

#else // defined _WIN32
class NCNN_EXPORT Mutex
{
Expand Down Expand Up @@ -186,7 +205,30 @@ public:
private:
pthread_key_t key;
};

#if (__cplusplus < 201103L) || NCNN_SIMPLESTL
typedef pthread_once_t OnceFlag;
#define OnceFlagInit PTHREAD_ONCE_INIT

static inline int CallOnce(OnceFlag &flag, void (*init_routine)(void))
{
return pthread_once(&flag, init_routine);
}
#endif // < c++11

#endif // defined _WIN32

#if (__cplusplus >= 201103L) && !NCNN_SIMPLESTL
using OnceFlag = std::once_flag;
#define OnceFlagInit {}

static inline int CallOnce(OnceFlag &flag, void (*init_routine)(void))
{
std::call_once(flag, init_routine);
return 0;
}
#endif // >= c++11

#else // NCNN_THREADS
class NCNN_EXPORT Mutex
{
Expand Down Expand Up @@ -225,6 +267,21 @@ public:
private:
void* data;
};

typedef bool OnceFlag;
#define OnceFlagInit false

static inline int CallOnce(OnceFlag &flag, void (*init_routine)(void))
{
if (!flag)
{
init_routine();
flag = true;
}

return 0;
}

#endif // NCNN_THREADS

class NCNN_EXPORT MutexLockGuard
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ endif()

ncnn_add_test(c_api)
ncnn_add_test(cpu)
ncnn_add_test(platform)

if(NCNN_VULKAN)
ncnn_add_test(command)
Expand Down
33 changes: 33 additions & 0 deletions tests/test_platform.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <stdlib.h>

#include "platform.h"

static int g_once_count = 0;

static void init()
{
g_once_count++;
}

int test_call_once()
{
static ncnn::OnceFlag flag = OnceFlagInit;
ncnn::CallOnce(flag, &init);
ncnn::CallOnce(flag, &init);
ncnn::CallOnce(flag, &init);

if (g_once_count != 1)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}

int main()
{
int ret;

ret = test_call_once();
if (ret)
return ret;

return 0;
}

0 comments on commit 0ca79c8

Please sign in to comment.