原计划是开始学习cocos2dx socket客户端的开发,
在网上查了些资料,说为了防止程序假死,需要另起线程处理网络连接。
好吧,那就从创建线程开始。
这次我的环境是在Mac下。在网上查阅和参考了很多资料,感谢这些无私奉献的前辈们的努力。
进入话题。
头文件:
- pthread_t th_socket; // 起这个名字本打算用在socket上的
- int threadStart();// 启动线程的方法
- static void* thread_funcation(void *arg);// 被启动的线程函数,注意必须是静态方法
函数定义:(我最喜欢把我的练习都写在HelloWorld类里面了,哈哈)
- // 启动线程的方法
- int HelloWorld::threadStart()
- {
- int errCode=0;
- do {
- pthread_attr_t tAttr;
- errCode=pthread_attr_init(&tAttr);
- CC_BREAK_IF(errCode!=0);
- errCode=pthread_attr_setdetachstate(&tAttr, PTHREAD_CREATE_DETACHED);
- if(errCode!=0)
- {
- pthread_attr_destroy(&tAttr);
- break;
- }
- errCode=pthread_create(&th_socket, &tAttr, thread_funcation, this);
-
- } while (0);
- return errCode;
- }
-
- // 需要线程来完成的功能都写在这个函数里
- void* HelloWorld::thread_funcation(void *arg)
- {
- CCLOG("thread started...");
- return NULL;
- }
然后我在HelloWorld::init()方法的后面加了一句代码来启动新线程:
编译后运行:
在输出窗口中可以看到:

说明线程正确执行。
|