cocos2dx创建线程

转自:http://blog.csdn.net/weyson/article/details/7865414


为了防止程序假死,需要另起线程处理网络连接。

好吧,那就从创建线程开始。

这次我的环境是在Mac下。在网上查阅和参考了很多资料,感谢这些无私奉献的前辈们的努力。

进入话题。

头文件:

[cpp]  view plain copy
  1. pthread_t th_socket; // 起这个名字本打算用在socket上的  
  2. int threadStart();// 启动线程的方法  
  3. static void* thread_funcation(void *arg);// 被启动的线程函数,注意必须是静态方法  

函数定义:(我最喜欢把我的练习都写在HelloWorld类里面了,哈哈)

[cpp]  view plain copy
  1. // 启动线程的方法  
  2. int HelloWorld::threadStart()  
  3. {  
  4.     int errCode=0;  
  5.     do {  
  6.         pthread_attr_t tAttr;  
  7.         errCode=pthread_attr_init(&tAttr);  
  8.         CC_BREAK_IF(errCode!=0);  
  9.         errCode=pthread_attr_setdetachstate(&tAttr, PTHREAD_CREATE_DETACHED);  
  10.         if(errCode!=0)  
  11.         {  
  12.             pthread_attr_destroy(&tAttr);  
  13.             break;  
  14.         }  
  15.         errCode=pthread_create(&th_socket, &tAttr, thread_funcation, this);  
  16.           
  17.     } while (0);  
  18.     return errCode;  
  19. }  
  20.   
  21. // 需要线程来完成的功能都写在这个函数里  
  22. void* HelloWorld::thread_funcation(void *arg)  
  23. {  
  24.     CCLOG("thread started...");  
  25.     return NULL;  
  26. }  
然后我在HelloWorld::init()方法的后面加了一句代码来启动新线程:

[cpp]  view plain copy
  1. this->threadStart();  

编译后运行:

在输出窗口中可以看到:

说明线程正确执行。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值