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)\n", GetThreadID(), s_nThreadResult);
}

void * theThread(void * param)
{
	// 通过once的控制,thread_init只会被执行一次
	pthread_once(&once, &thread_init);
	printf("[Child %0.4x] looping i(%0.8x)\n", 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\n", *(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\n", *(int *)status);
	}

	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值