一个关于apue里的问题

来源:百度知道 编辑:UC知道 时间:2024/05/10 05:28:39
apue里有这一段:
We need to ensure that a key we allocate doesn't change because of a race during initialization. Code like the following can result in two threads both calling pthread_key_create:

void destructor(void *);

pthread_key_t key;
int init_done = 0;

int
threadfunc(void *arg)
{
if (!init_done) {
init_done = 1;
err = pthread_key_create(&key, destructor);
}
...
}

Depending on how the system schedules threads, some threads might see one key value, whereas other threads might see a different value.

这段看不懂,为什么导致两个线程都调用pthread_key_create

如果同时定义了2个pthread_t tid1, tid2;
然后创建了2个线程采用同一个线程callback函数pthread_create(&tid1, NULL, threadfunc, 1); pthread_create(&tid2, NULL, threadfunc, 2); 那么就会同时调用pthread_key_create函数.
因为pthread_key_create函数在线程处理函数中, 线程又是并行运行的.

apue是本好书啊......