在cocos2d-x里面用多线程还是乖乖的用pthread吧。应用一启动时创建线程作为逻辑线程。
创建方法如下:
extern ResourcePool logicThreadResource;
void *test(void *param){
while (true) {
if (logicThreadResource.peekNextDataLength()) {
printf("有数据需要处理");
int datasize = 0;
char *receiveData = new char[512];
logicThreadResource.popData(receiveData, datasize, 512);
int sigal = *((int32_t *) receiveData);
printf("the sigal is %d\n", sigal);
if (sigal == 100) {
CalWinRate(receiveData+4);
}
delete[] receiveData;
}else{
pthread_mutex_lock(&locklogicthread);
pthread_cond_wait(&cond, &locklogicthread);
pthread_mutex_unlock(&locklogicthread);
}
}
return NULL;
}
void create_pthread(){
// 启动两个测试的主线程
pthread_t tid;
pthread_create(&tid, NULL, test, NULL);
}
pthread_create原型为:PTW32_DLLPORT int PTW32_CDECL pthread_create(pthread_t *tid, const pthread_attr_t *attr, void*(*start)(void *), void *arg)。create有四个参数,第一个是pthread_t,第二个是创建线程的参数,第三个是线程的入口函数,第四个为入口函数参数。这里需要注意的是设置pthread_cond_wait即唤醒函数的时候一定要加锁。启动函数如下:
bool ResourcePool::pushData(const char *data, int size){
AutoReleaseLock myLock = AutoReleaseLock();
// deal
int realSize = size + sizeof(int32_t);
int needMemory = bufferLength + realSize;
if (needMemory > bufferCapacity) {
// 需要重新分配内存
if (reMollocMemory(needMemory)) {
}else{
return false;
}
}
//
char *pWriteBuff = resPool + bufferLength;
*((int32_t *)pWriteBuff) = size;
pWriteBuff += sizeof(int32_t);
bufferLength += sizeof(int32_t);
memmove(pWriteBuff, data, size);
bufferLength += size;
// 缓冲区有数据的话就激活线程
pthread_cond_signal(&cond);
return true;
}
思路还是采用的是我上篇博客的思路,至于cocos2d-x里面的调用我是这样的:
local handler
local scheduler = CCDirector:sharedDirector():getScheduler()
handler = scheduler:scheduleScriptFunc(function()
-- 每帧检测一下数据,看看是否是合理的
BookUtils:parsePackageToLua()
if GLOABLEPACKAGE ~= "" then
-- 解析数据
local package = json.decode(GLOABLEPACKAGE)
print("the GLOABLEPACKAGE is " .. GLOABLEPACKAGE)
GLOABLEPACKAGE = ""
local dataTable = {}
table.walk(package, function(val, key)
if tonumber(key) ~= 1 then
dataTable[#dataTable+1] = val
end
end)
if tonumber(package[1]) == 100 then
-- 胜率计算器,更新胜率
CCNotificationCenter:sharedNotificationCenter():postNotification("CAL_WIN_RATE_UPDATE", CCString:create(json.encode(dataTable)))
elseif tonumber(package[1]) == 101 then
-- 胜率计算完毕
CCNotificationCenter:sharedNotificationCenter():postNotification("CAL_WIN_RATE_UPDATE_END")
end
end
end, 0, false)
即主线程每一帧去检测缓冲区,如果有数据,则发送消息。