【Cocos2d-x】pthread库的使用


pthread库是一个跨平台的多线程库。在Cocos2d-x中已经集成了该库。


工程配置


1.包含头文件

$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\pthread



2.链接库文件

pthreadVCE2.lib




使用pthread库



相关api说明


互斥锁:
//定义互斥锁
pthread_mutex_t  s_taskQueueMutex;
// 初始化互斥锁
pthread_mutex_init(&s_taskQueueMutex, NULL);
//销毁互斥锁
pthread_mutex_destroy(&s_taskQueueMutex);

条件变量:
// 定义条件变量
pthread_mutex_t s_SleepMutex;
pthread_cond_t s_SleepCondit

// 初始化条件变量
pthread_mutex_init(&s_SleepMutex, NULL);
pthread_cond_init(&s_SleepCondition, NULL);

//销毁条件变量
pthread_mutex_destroy(&s_SleepMutex);
pthread_cond_destroy(&s_SleepCondition);

条件变量是利用线程间共享的 全局变量 进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。为了防止竞争, 条件变量 的使用总是和一个 互斥锁 结合在一起。

线程:
//线程id
static pthread_t s_workThread;

//定义线程方法
static void* workThread(void *data){
//do something
return 0;
}

// 创建线程
pthread_create(&s_workThread, NULL, workThread, NULL);
// 执行线程
pthread_detach(s_workThread);
//退出当前线程
pthread_exit(NULL);


示例代码


//包含头文件
#include <pthread.h>

//线程id
static pthread_t s_workThread;

static void* workThread(void *data){

	CCLOG("workThead running");

	for (int i=1;i<30;++i)
	{
		CCLOG("child thread 1 num=%d",i);
	}	

	//退出当前线程
	pthread_exit(NULL);

	return 0;
}

void AppDelegate::threadTest(){
	// 创建线程
	pthread_create(&s_workThread, NULL, workThread, NULL);
	// 执行线程
	pthread_detach(s_workThread);		
}

调用代码如下:
	this->threadTest();
	CCLOG("main thread running..");

日志输出如下:


从日志可以看到“main thread running"先被输出了,也就是说theadTest()方法中创建和执行的线程方法并没有阻塞主线程代码的执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值