易网时代-编程资源站
Welcome
微信登录
编程资源
图片资源库
蚂蚁家优选
PDF转换器
软件资源
软件开发
、
小程序制作
、
系统集成与运维
、
空间租用
、
硬件开发
、
视频监控
、
技术咨询与支持
——联系电话:0311-88999002/88999003
首页
/
操作系统
/
Linux
/
POSIX的只执行一次的pthread_once
POSIX的只执行一次的pthread_once
#ifdef WIN32
#include <windows.h>
#define SLEEP(ms) Sleep(ms)
#else if defined(LINUX)
#include <stdio.h>
#define SLEEP(ms) sleep(ms)
#endif
#include <cassert>
#include <pthread.h>
// 取出线程的ID
int
GetThreadID()
{
#ifdef WIN32
return
(
int
)pthread_getw32threadhandle_np( pthread_self() );
#else if defined(LINUX)
return
(
int
)pthread_self();
#endif
}
// 该静态变量被所有线程使用
static
int
s_nThreadResult = 0;
static
pthread_once_t once = PTHREAD_ONCE_INIT;
// 该初始化函数,我在多线程下只想执行一次
void
thread_init()
{
s_nThreadResult = -1;
printf(
"[Child %0.4x] looping i(%0.8x) "
, GetThreadID(), s_nThreadResult);
}
void
* theThread(
void
* param)
{
// 通过once的控制,thread_init只会被执行一次
pthread_once(&once, &thread_init);
printf(
"[Child %0.4x] looping i(%0.8x) "
, GetThreadID(), s_nThreadResult);
s_nThreadResult ++;
pthread_exit(&s_nThreadResult);
return
NULL;
}
int
main(
int
argc,
char
* argv[])
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, &theThread, NULL);
pthread_create(&tid2, NULL, &theThread, NULL);
// 无论是否休眠,两个子线程最终都会被主线程join到
// 因为两个子线程都是默认的PTHREAD_CREATE_JOINABLE类型
//SLEEP(3);
void
* status = NULL;
int
rc = pthread_join(tid1, &status);
assert(rc == 0 &&
"pthread_join 1"
, rc);
if
(status != PTHREAD_CANCELED && status != NULL)
{
printf(
"Returned value from thread: %d "
, *(
int
*)status);
}
rc = pthread_join(tid2, &status);
assert(rc == 0 &&
"pthread_join 2"
, rc);
if
(status != PTHREAD_CANCELED && status != NULL)
{
printf(
"Returned value from thread: %d "
, *(
int
*)status);
}
return
0;
}
收藏该网址
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图