分享

cocos2dx创建线程

 勤奋不止 2013-12-13

原计划是开始学习cocos2dx socket客户端的开发,

在网上查了些资料,说为了防止程序假死,需要另起线程处理网络连接。

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

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

进入话题。

头文件:

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

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

  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()方法的后面加了一句代码来启动新线程:

  1. this->threadStart();  

编译后运行:

在输出窗口中可以看到:

说明线程正确执行。



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多