标签:同方 才干 没有 _id style state set str std
尽管内容是抄过来的。可是经过了我的验证。并且放在一起就清楚非常多了,cocos2dx版本号常常变化非常大。总会导致这样那样的问题。
#include <pthread.h>
...
pthread_t serial_thread_id; // 起这个名字本打算用在socket上的
int serialThreadStart(void);// 启动线程的方法
static void* serialReceiverFun(void *arg);// 被启动的线程函数,注意必须是静态方法
......
int HelloWorld::serialThreadStart()
{
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(&serial_thread_id, &tAttr, serialReceiverFun, this);
CCLOGERROR("serial_thread_id=%d\n",&serial_thread_id);
} while (0);
return errCode;
}
void* HelloWorld::serialReceiverFun(void *arg)
{
CCLOGERROR("serial thread start");
while(true)
{
char buff[BUFSIZE]={0};
int readSize = 0;
readSize = receiverDate(buff,BUFSIZE);
if(readSize > 0)
{
CCLOGERROR("readSize=%d,%s\n",readSize,buff);
sendDate(buff,readSize);
}
}
return NULL;
}
...this->serialThreadStart();
但在cocos2dx 3.0中并未发现有pthread的支持文件。原来c++11中已经拥有了一个更好用的用于线程操作的类std::thread。cocos2dx 3.0的版本号默认是在vs2012版本号,支持c++11的新特性,使用std::thread来创建线程简直方便。
#include <thread>
...
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
std::thread t1(&HelloWorld::myThread,this);//创建一个分支线程,回调到myThread函数里
// t1.join();
t1.detach();
CCLOG("in major thread");//在主线程
return true;
}
void HelloWorld::myThread()
{
CCLOG("in my thread");
}分离后的线程,主线程将对它没有控制权了。
以下样例在实例化线程对象的时候,在线程函数myThread后面紧接着传入两个參数。
#include <thread>
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
std::thread t1(&HelloWorld::myThread,this,10,20);//创建一个分支线程,回调到myThread函数里
//t1.join();
t1.detach();
CCLOG("in major thread");//在主线程
return true;
}
void HelloWorld::myThread(int first,int second)
{
CCLOG("in my thread,first = %d,second = %d",first,second);
}
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
std::thread t1(&HelloWorld::myThread,this,10,20);//创建一个分支线程。回调到myThread函数里
//t1.join();
t1.detach();
CCLOG("in major thread");//在主线程
return true;
}
void HelloWorld::myThread(int first,int second)
{
CCLOG("in my thread,first = %d,second = %d",first,second);
}
cocos2dx2.0 与cocos2dx3.1 创建线程不同方式总结
标签:同方 才干 没有 _id style state set str std
原文地址:http://www.cnblogs.com/zhchoutai/p/6994670.html