您的位置:首页 > 其它

pthread_once

2015-06-28 16:33 295 查看
无论多少线程调用这个函数,only run一次:

如果对现有的某个线程的终止状态不感兴趣,可以使用pthread_detach函数让操作系统在线程退出时收回它所占用的资源。

很多函数并不是线程安全的,因为他们返回的数据是存放在静态的内存缓冲区中。通过修改接口,要求调用者自己提供缓冲区可以使函数变为线程安全的。

pthread_once 无论多少个线程,只被执行一次,有一个线程执行了,其他的就不run了。

int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

static pthread_key_t pid_key;

pid_key是线程的私有全局变量,不是进程的全局变量。就是说各个线程同名,都是在各个线程独立。不互相影响。线程也有自己的global变量,本线程的各个函数是global的。

destructor是当线程结束的时候,clean 线程的global变量。如close file。

pthread_once 和pthread_key_t pid 什么关系呢。

一定连用。就pid会只需并且必须创建一次。 但是各个线程都可以用。

私有的线程private 变量,和进程的global变量,用法不一样,不是在global的位置,如定义int a;

而是用私有的local变量赋予这个私有global的变量。用pthread_setspecific(key, envbuf);

然后在其他的函数用pthread_getspecific获取私有global的变量。

include <pthread.h>

#include <stdlib.h>

//global var in one thread

static pthread_key_t pid_key;

pthread_once_t once = PTHREAD_ONCE_INIT;

void

once_run(void)

{

int ret=0;

static int times=1;

ret = pthread_key_create(&pid_key,NULL);

if (ret==0)

{

printf("private key create succes ,by %u\n",pthread_self());

}

printf("The %d time run\n",times);

times++;

}

void*

child(void *arg)

{

pthread_t tid=pthread_self();

printf("Thread %u is run!\n",tid);

pthread_once(&once,once_run);

//set private value

pthread_setspecific(pid_key,&tid);

while (1)

{

printf("child:%d,private key%d\n",

pthread_self(),(int)pthread_getspecific(pid_key));

sleep(1);

}

printf("Thread %u is quit!\n",tid);

return 0;

}

int

main ()

{

pthread_t tid1,tid2;

pthread_create(&tid1,NULL,child,NULL);

pthread_create(&tid2,NULL,child,NULL);

pthread_join(tid1,NULL);

pthread_join(tid2,NULL);

printf("all exit!\n");

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: