Read Before Written

static struct worker *g_worker;      /* starts NULL */

void init(void) {                    /* thread 1 */
    g_worker = worker_create(worker_main, NULL);
}

void worker_main(void *unused) {     /* thread 2, started inside worker_create */
    int state = g_worker->state;     /* crashes here */
    ...
}

The new thread occasionally dereferences NULL on its very first line. Which fix is correct?

A

Point g_worker at a zeroed static struct at startup so the dereference never touches NULL.

B

Add an int inited = 0 guarded by a mutex and a condition variable: init sets it to 1 under the lock and signals, and worker_main runs while (inited == 0) pthread_cond_wait(...) before touching g_worker.

C

Call usleep(1000) at the top of worker_main so init has time to finish the assignment.

D

Declare g_worker as volatile struct worker * so the child always sees the current value.