param.h 2.14 KB
Newer Older
lishen's avatar
lishen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#pragma once

#include <stdint.h>

namespace sccl {

// 返回用户的主目录路径
const char* userHomeDir();

// 设置环境文件的名称
void setEnvFile(const char* fileName);

// 初始化环境变量
void initEnv();

// 加载参数,如果环境变量未设置,则使用默认值
void scclLoadParam(char const* env, int64_t deftVal, int64_t uninitialized, int64_t* cache);

// 设置线程名称,使用可变参数格式化字符串
void scclSetThreadName(pthread_t thread, const char* fmt, ...);

/**
 * 定义SCCL参数宏。
 * 此宏用于创建一个获取SCCL参数的函数。
 * 参数通过环境变量获取,若环境变量未设置,则使用默认值。
 *
 * @param name 参数名称
 * @param env 环境变量名称
 * @param deftVal 默认值
 *
 * @return 返回参数的值
 *
 * 宏内部实现:
 * - 使用constexpr定义一个未初始化的值。
 * - 使用static_assert确保默认值不是未初始化的值。
 * - 定义一个静态变量cache用于缓存参数值,初始为未初始化的值。
 * - 使用__builtin_expect和__atomic_load_n检查cache是否为未初始化的值。
 * - 若cache未初始化,则调用scclLoadParam函数加载参数值。
 * - 返回cache的值。
 */
#define SCCL_PARAM(name, env, deftVal)                                                               \
    int64_t scclParam##name() {                                                                      \
        constexpr int64_t uninitialized = INT64_MIN;                                                 \
        static_assert(deftVal != uninitialized, "default value cannot be the uninitialized value."); \
        static int64_t cache = uninitialized;                                                        \
        if(__builtin_expect(__atomic_load_n(&cache, __ATOMIC_RELAXED) == uninitialized, false)) {    \
            scclLoadParam("SCCL_" env, deftVal, uninitialized, &cache);                              \
        }                                                                                            \
        return cache;                                                                                \
    }

} // namespace sccl