【Cocos2d-x】pthread库的使用
发布时间:2020-12-14 19:36:50 所属栏目:百科 来源:网络整理
导读:pthread库是一个跨平台的多线程库。在Cocos2d-x中已经集成了该库。 工程配置 1.包含头文件 $(ProjectDir)......cocos2dxplatformthird_partywin32pthread 2.链接库文件 pthreadVCE2.lib 使用pthread库 相关api说明 互斥锁: //定义互斥锁 pthread_mut
pthread库是一个跨平台的多线程库。在Cocos2d-x中已经集成了该库。
工程配置
1.包含头文件 $(ProjectDir)......cocos2dxplatformthird_partywin32pthread
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); // 执行线程 pthread_detach(s_workThread); }
调用代码如下:
this->threadTest(); CCLOG("main thread running..");
日志输出如下:
从日志可以看到“main thread running"先被输出了,也就是说theadTest()方法中创建和执行的线程方法并没有阻塞主线程代码的执行。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |