• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef JS_CONCURRENT_MODULE_COMMON_HELPER_CONCURRENT_HELPER_H
17 #define JS_CONCURRENT_MODULE_COMMON_HELPER_CONCURRENT_HELPER_H
18 
19 #include <chrono>
20 #include <uv.h>
21 #if defined(OHOS_PLATFORM)
22 #include <unistd.h>
23 #elif defined(WINDOWS_PLATFORM)
24 #include <windows.h>
25 #elif defined(MAC_PLATFORM) || defined(IOS_PLATFORM)
26 #include <sys/sysctl.h>
27 #elif defined(ANDROID_PLATFORM)
28 #include <sys/sysinfo.h>
29 #endif
30 
31 #if __GNUC__
32 #define LIKELY(x) __builtin_expect(!!(x), 1)
33 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
34 #else
35 #define LIKELY(x) (!!(x))
36 #define UNLIKELY(x) (!!(x))
37 #endif // __GNUC__
38 
39 namespace Commonlibrary::Concurrent::Common::Helper {
40 class ConcurrentHelper {
41 public:
42     ConcurrentHelper() = delete;
43     ~ConcurrentHelper() = delete;
44 
GetMaxThreads()45     static uint32_t GetMaxThreads()
46     {
47 #if defined(OHOS_PLATFORM)
48         return sysconf(_SC_NPROCESSORS_ONLN) - 1;
49 #elif defined(WINDOWS_PLATFORM)
50         SYSTEM_INFO sysInfo;
51         GetSystemInfo(&sysInfo);
52         return sysInfo.dwNumberOfProcessors - 1;
53 #elif defined(MAC_PLATFORM) || defined(IOS_PLATFORM)
54         int32_t numCpu = 0;
55         size_t size = sizeof(numCpu);
56         sysctlbyname("hw.ncpu", &numCpu, &size, nullptr, 0);
57         return numCpu - 1;
58 #elif defined(ANDROID_PLATFORM)
59         return get_nprocs() - 1;
60 #else
61         return 1; // 1: default number
62 #endif
63     }
64 
GetMilliseconds()65     static uint64_t GetMilliseconds()
66     {
67         auto now = std::chrono::system_clock::now();
68         auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
69         return millisecs.count();
70     }
71 
72     template<typename T>
UvHandleClose(T * handle)73     static void UvHandleClose(T* handle)
74     {
75         uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
76             if (handle != nullptr) {
77                 delete reinterpret_cast<T*>(handle);
78                 handle = nullptr;
79             }
80         });
81     }
82 };
83 } // namespace Commonlibrary::Concurrent::Common::Helper
84 #endif // JS_CONCURRENT_MODULE_COMMON_HELPER_CONCURRENT_HELPER_H