简体   繁体   English

在 C 中实现延迟初始化

[英]Implementing lazy initialisation in C

In C++, I can implement lazy initialisation with static :在 C++ 中,我可以使用static实现延迟初始化:

struct foo { ... };
foo create_foo();
const foo& get_foo() {
    static foo x = create_foo();
    return x;
}

Here, initialisation occurs the first time get_foo is called (lazy), get_foo is guaranteed to be thread safe, and initialisation is guaranteed to only occur once.在这里,初始化在第一次get_foo时发生(惰性),保证get_foo是线程安全的,并且保证初始化只发生一次。 Specifically:具体来说:

[stmt.dcl] "Dynamic initialization of a block-scope variable with static storage duration... is performed the first time control passes through its declaration... if control enters the declaration concurrently... the concurrent execution shall wait for completion of the initialization" [stmt.dcl]“具有 static 存储持续时间的块范围变量的动态初始化...在控制第一次通过其声明时执行...如果控制同时进入声明...并发执行应等待完成初始化"

How can I get the same behaviour in standard C?如何在标准 C 中获得相同的行为?

In C, there are no references, and you have to type struct , and you have to take care of initialization.在 C 中,没有引用,您必须键入struct ,并且必须注意初始化。

#include <stdbool.h>
struct foo { int a; };
struct foo create_foo();
const struct foo* get_foo() {
    static bool initialized = false;
    static struct foo x;
    if (!initialized) {
        initialized = true;
        x = create_foo();
    }
    return &x;
}

To be thread-safe, you can use call_once .为了线程安全,您可以使用call_once Sadly, with a global variable.可悲的是,有一个全局变量。

#include <threads.h>
struct foo { int a; };
struct foo create_foo();

static struct foo global_x;
static void init_global_x(void) {
    global_x = create_foo();
}
const struct foo* get_foo() {
    static once_flag global_x_initialized = ONCE_FLAG_INIT;
    call_once(&global_x_initialized , init_global_x);
    return &global_x;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM