当前位置: 首页>>代码示例>>C++>>正文


C++ CCThread类代码示例

本文整理汇总了C++中CCThread的典型用法代码示例。如果您正苦于以下问题:C++ CCThread类的具体用法?C++ CCThread怎么用?C++ CCThread使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了CCThread类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: waitingConnectThreadEntry

void* CCTCPSocket::waitingConnectThreadEntry(void* arg) {
	// autorelease pool
	CCThread thread;
	thread.createAutoreleasePool();
	
	// get socket
	CCTCPSocket* s = (CCTCPSocket*)arg;
	
	// select it
	timeval timeout;
	timeout.tv_sec = s->m_blockSec;
	timeout.tv_usec = 0;
	fd_set writeset, exceptset;
	FD_ZERO(&writeset);
	FD_ZERO(&exceptset);
	FD_SET(s->m_sock, &writeset);
	FD_SET(s->m_sock, &exceptset);
	int ret = select(FD_SETSIZE, NULL, &writeset, &exceptset, &timeout);
	if (ret < 0) {
		s->destroy();
	} else {
		ret = FD_ISSET(s->m_sock, &exceptset);
		if(ret) {
			s->destroy();
		} else {
			s->m_connected = true;
		}
	}
	
	// release
	s->autorelease();
	
	return NULL;
}
开发者ID:DEVMIX-APPS,项目名称:cocos2dx-better,代码行数:34,代码来源:CCTCPSocket.cpp

示例2: loadString

static void* loadString(void* data)
{
    
    AsyncStringStruct *pAsyncStruct = NULL;
    
    while (true)
    {
        // create autorelease pool for iOS
        CCThread thread;
        thread.createAutoreleasePool();
        
        std::queue<AsyncStringStruct*> *pQueue = s_pAsyncStringStructQueue;
        pthread_mutex_lock(&s_asyncStructStringQueueMutex);// get async struct from queue
        CCLog("*-*-*-*-*-%d",pQueue->empty());
        if (pQueue->empty())
        {
            pthread_mutex_unlock(&s_asyncStructStringQueueMutex);
            CCLog("need_quit1    %d",need_quit1);
            if (need_quit1) {
                break;
            }
            else {
                pthread_cond_wait(&s_SleepStringCondition, &s_SleepStringMutex);
                continue;
            }
        }
        else
        {
            pAsyncStruct = pQueue->front();
            pQueue->pop();
            pthread_mutex_unlock(&s_asyncStructStringQueueMutex);
            loadStringData(pAsyncStruct);
        }
    }
    
    if( s_pAsyncStringStructQueue != NULL )
    {
        
        delete s_pAsyncStringStructQueue;
        s_pAsyncStringStructQueue = NULL;
        delete s_pStringQueue;
        s_pStringQueue = NULL;
        
        pthread_mutex_destroy(&s_asyncStructStringQueueMutex);
        pthread_mutex_destroy(&s_StringInfoMutex);
        pthread_mutex_destroy(&s_SleepStringMutex);
        pthread_cond_destroy(&s_SleepStringCondition);
    }
    
    return 0;
}
开发者ID:Jimlan,项目名称:CrossApp,代码行数:51,代码来源:CCTextureCache.cpp

示例3: requestThread

void* CCMessageQueue::requestThread(void* data)
{
    // create autorelease pool for iOS
    CCThread thread;
    thread.createAutoreleasePool();
    
    while (!m_bQuit)
    {
        // wait for sem_post
        int semWaitRet = sem_wait(s_pSem);
        if( semWaitRet < 0 )
        {
            CCLOG( "CCTextureCache async thread semaphore error: %s\n", strerror( errno ) );
            break;
        }
        
        RequestInfo *pRequestInfo = CCMessageQueue::sharedMessagequeue()->popUpRequest();
        if (!pRequestInfo)
        {
            continue;
        }
        
        if (!pRequestInfo->requestMode) 
        {
            pRequestInfo->stateCode = CCHttpClient::sharedHttpClient()->Get(pRequestInfo->strUrl, pRequestInfo->strResponseData);
        }
        else 
        {
            pRequestInfo->stateCode = CCHttpClient::sharedHttpClient()->Post(pRequestInfo->strUrl, pRequestInfo->strRequestData, pRequestInfo->strResponseData);
        }
        
        CCTime::gettimeofdayCocos2d(&pRequestInfo->responseTime, NULL);

        sem_post(s_pSemResponse);
    }
    
    if( s_pSem != NULL )
    {
#if CC_ASYNC_TEXTURE_CACHE_USE_NAMED_SEMAPHORE
        sem_unlink(CC_ASYNC_TEXTURE_CACHE_SEMAPHORE);
        sem_close(s_pSem);
#else
        sem_destroy(s_pSem);
#endif
        s_pSem = NULL;
    }
    
    return 0;
}
开发者ID:CommonSenseLies,项目名称:LuckyCat,代码行数:49,代码来源:CCMessagequeue.cpp

示例4: responseThread

void* CCMessageQueue::responseThread(void* data)
{
    // create autorelease pool for iOS
    CCThread thread;
    thread.createAutoreleasePool();
    
    while (!m_bQuit)
    {
        // wait for sem_post
        int semWaitRet = sem_wait(s_pSemResponse);
        if( semWaitRet < 0 )
        {
            CCLOG( "CCTextureCache async thread semaphore error: %s\n", strerror( errno ) );
            break;
        }
        
        RequestInfo *pRequestInfo = NULL;
        while (true) 
        {
            pRequestInfo = CCMessageQueue::sharedMessagequeue()->popUp();
            if (!pRequestInfo)
            {
                break;
            }   
                
            CCCallbackNode* pCallbackNode = CCMessageQueue::sharedMessagequeue()->getCallbackNode();
            if(pCallbackNode)
            {
                pCallbackNode->callback(pRequestInfo);
            }
            
        }
    }
    
    if( s_pSemResponse != NULL )
    {
#if CC_ASYNC_TEXTURE_CACHE_USE_NAMED_SEMAPHORE
        sem_unlink(CC_ASYNC_TEXTURE_CACHE_SEMAPHORE_RESPONSE);
        sem_close(s_pSemResponse);
#else
        sem_destroy(s_pSemResponse);
#endif
        s_pSemResponse = NULL;
    }
    
    return 0;
}
开发者ID:CommonSenseLies,项目名称:LuckyCat,代码行数:47,代码来源:CCMessagequeue.cpp

示例5: loadImage

static int loadImage(void* data)
{
    AsyncStruct *pAsyncStruct = NULL;

    while (true)
    {
        // create autorelease pool for iOS
        CCThread thread;
        thread.createAutoreleasePool();

        std::queue<AsyncStruct*> *pQueue = s_pAsyncStructQueue;
        mtx_lock(&s_asyncStructQueueMutex);// get async struct from queue
        if (pQueue->empty())
        {
            mtx_unlock(&s_asyncStructQueueMutex);
            if (need_quit) {
                break;
            }
            else {
                cnd_wait(&s_SleepCondition, &s_SleepMutex);
                continue;
            }
        }
        else
        {
            pAsyncStruct = pQueue->front();
            pQueue->pop();
            mtx_unlock(&s_asyncStructQueueMutex);
            loadImageData(pAsyncStruct);
        }        
    }
    
    if( s_pAsyncStructQueue != NULL )
    {
        delete s_pAsyncStructQueue;
        s_pAsyncStructQueue = NULL;
        delete s_pImageQueue;
        s_pImageQueue = NULL;

        mtx_destroy(&s_asyncStructQueueMutex);
        mtx_destroy(&s_ImageInfoMutex);
        mtx_destroy(&s_SleepMutex);
        cnd_destroy(&s_SleepCondition);
    }
    
    return 0;
}
开发者ID:fordream,项目名称:quick,代码行数:47,代码来源:CCTextureCache.cpp

示例6: while

// new update tiles for threaded use
void *CCBigImage::updateTilesInThread(void *ptr)
{
    CCThread thread;
    thread.createAutoreleasePool();
    
    CCBigImage* bigImage = (CCBigImage*)ptr;
    
	while(!bigImage->_tilesLoadThreadCancel)
	{
        CCThread thread;
        thread.createAutoreleasePool();
        
		// flag for removeUnusedTextures only when sleeping - to disable deadLocks
		bigImage->_tilesLoadThreadIsSleeping = false;
		
        if (bigImage->_tilesLoadThreadCancel) return NULL;
        if (bigImage->_dynamicChildren==NULL) return NULL;
        int count = bigImage->_dynamicChildren->count();
		for (int i=0; i<count; i++)
        {
            if (bigImage->_tilesLoadThreadCancel || bigImage->_dynamicChildren==NULL) break;
            UnloadableSpriteNode *child = (UnloadableSpriteNode*)(bigImage->_dynamicChildren->objectAtIndex(i));
			if (!child->boundingBox().intersectsRect(bigImage->_loadedRect)) {
				child->unload();
            } else {
				child->load(bigImage->_textureCache);;
            } //< 0 == size.width must be faster than CGRectIsEmpty
		}
        
		// flag removeUnusedTextures only when sleeping - to disable deadLocks
		bigImage->_tilesLoadThreadIsSleeping = true;
		
		// 60 FPS run, update at 30 fps should be ok
        usleep(30*1000);
	}
    
    return NULL;
}
开发者ID:DPigpen,项目名称:cocos2dx_recipe,代码行数:39,代码来源:CCBigImage.cpp

示例7: loadImage

static void* loadImage(void* data)
{
    AsyncStruct *pAsyncStruct = NULL;

    while (true)
    {
        // create autorelease pool for iOS
        CCThread thread;
        thread.createAutoreleasePool();

        std::queue<AsyncStruct*> *pQueue = s_pAsyncStructQueue;
        pthread_mutex_lock(&s_asyncStructQueueMutex);// get async struct from queue
        if (pQueue->empty())
        {
            pthread_mutex_unlock(&s_asyncStructQueueMutex);
            if (need_quit) {
                break;
            }
            else {
            	pthread_cond_wait(&s_SleepCondition, &s_SleepMutex);
                continue;
            }
        }
        else
        {
            pAsyncStruct = pQueue->front();
            pQueue->pop();
            pthread_mutex_unlock(&s_asyncStructQueueMutex);
        }        

        const char *filename = pAsyncStruct->filename.c_str();

        // compute image type
        CCImage::EImageFormat imageType = computeImageFormatType(pAsyncStruct->filename);
        if (imageType == CCImage::kFmtUnKnown)
        {
            CCLOG("unsupported format %s",filename);
            delete pAsyncStruct;
            
            continue;
        }
        
        // generate image            
        CCImage *pImage = new CCImage();
        if (pImage && !pImage->initWithImageFileThreadSafe(filename, imageType))
        {
            CC_SAFE_RELEASE(pImage);
            CCLOG("can not load %s", filename);
            continue;
        }

        // generate image info
        ImageInfo *pImageInfo = new ImageInfo();
        pImageInfo->asyncStruct = pAsyncStruct;
        pImageInfo->image = pImage;
        pImageInfo->imageType = imageType;

        // put the image info into the queue
        pthread_mutex_lock(&s_ImageInfoMutex);
        s_pImageQueue->push(pImageInfo);
        pthread_mutex_unlock(&s_ImageInfoMutex);    
    }
    
    if( s_pAsyncStructQueue != NULL )
    {
        delete s_pAsyncStructQueue;
        s_pAsyncStructQueue = NULL;
        delete s_pImageQueue;
        s_pImageQueue = NULL;

        pthread_mutex_destroy(&s_asyncStructQueueMutex);
        pthread_mutex_destroy(&s_ImageInfoMutex);
        pthread_mutex_destroy(&s_SleepMutex);
        pthread_cond_destroy(&s_SleepCondition);
    }
    
    return 0;
}
开发者ID:walklook,项目名称:ThreadTile,代码行数:78,代码来源:CCTextureCache.cpp

示例8: udpThreadEntry

void* CCUDPSocket::udpThreadEntry(void* arg) {
    // autorelease pool
	CCThread thread;
	thread.createAutoreleasePool();
	
	// get socket
	CCUDPSocket* s = (CCUDPSocket*)arg;
	
    // client address
	sockaddr_in my_addr;
	my_addr.sin_family = AF_INET;
	my_addr.sin_addr.s_addr = INADDR_ANY;
	my_addr.sin_port = 0;
	
	// bind
	if(bind(s->m_socket, (sockaddr*)&my_addr, sizeof(my_addr)) == kCCSocketError && s->hasError()) {
        s->closeSocket();
	} else {
     	// select it
        timeval timeout;
        timeout.tv_sec = s->m_blockSec;
        timeout.tv_usec = 0;
        fd_set writeset, exceptset;
        FD_ZERO(&writeset);
        FD_ZERO(&exceptset);
        FD_SET(s->m_socket, &writeset);
        FD_SET(s->m_socket, &exceptset);
        int ret = select(FD_SETSIZE, NULL, &writeset, &exceptset, &timeout);
        if (ret == 0 || ret < 0) {
            s->closeSocket();
        } else {
            ret = FD_ISSET(s->m_socket, &exceptset);
            if(ret) {
                s->closeSocket();
            } else {
                s->m_connected = true;
                if(s->m_hub)
                    s->m_hub->onSocketConnectedThreadSafe(s);
            }
        }
    }
	
	// delay 500ms when socket closed
    struct linger so_linger;
    so_linger.l_onoff = 1;
    so_linger.l_linger = 500;
    setsockopt(s->m_socket, SOL_SOCKET, SO_LINGER, (const char*)&so_linger, sizeof(so_linger));
    
    // read/write loop
    CCPacket* p = NULL;
    while(!s->m_stop && s->m_connected && s->getSocket() != kCCSocketInvalid) {
        s->recvFromSock();
        if(s->m_inBufLen > 0) {
            CCPacket* p = NULL;
            if(s->m_hub) {
                if(s->m_hub->isRawPolicy()) {
                    p = CCPacket::createRawPacket(s->m_inBuf, s->m_inBufLen);
                } else {
                    p = CCPacket::createStandardPacket(s->m_inBuf, s->m_inBufLen);
                }
                s->m_hub->onPacketReceivedThreadSafe(p);
            }
        }
        
        // get packet to be sent
        if(!p && s->m_sendQueue.count() > 0) {
            pthread_mutex_lock(&s->m_mutex);
            p = (CCPacket*)s->m_sendQueue.objectAtIndex(0);
            CC_SAFE_RETAIN(p);
            s->m_sendQueue.removeObjectAtIndex(0);
            pthread_mutex_unlock(&s->m_mutex);
        }
        
        // send current packet
        if(p) {
            ssize_t sent = sendto(s->m_socket, p->getBuffer(), p->getPacketLength(), 0, (sockaddr*)&s->m_srvAddr, sizeof(s->m_srvAddr));
            if(sent >= p->getPacketLength()) {
                CC_SAFE_RELEASE(p);
                p = NULL;
            } else {
                if (s->hasError()) {
                    s->closeSocket();
                }
            }
        }
    }
    
    // end
    if(s->m_connected) {
        if(s->m_hub)
            s->m_hub->onSocketDisconnectedThreadSafe(s);
        s->m_connected = false;
    }
	
	// release
	s->autorelease();
    
    // exit
    pthread_exit(NULL);
	
//.........这里部分代码省略.........
开发者ID:GreatFireWall,项目名称:cocos2dx-better,代码行数:101,代码来源:CCUDPSocket.cpp

示例9: while

//Worker thread
static void *requestThread(void *data)
{
    data;
    CCThread thread;
    thread.createAutoreleasePool();
    
    HttpRequestPacket *req = NULL;
    
    while (true) {
        //Wait for http request tasks from main thread
        int semWaitRet = sem_wait(s_pSem);
        if (semWaitRet < 0) {
            CCLog("HttpRequest async thread semaphore error: %s\n", strerror(errno));
            break;
        }
        
        std::queue<HttpRequestPacket *> *pQueue = s_requestQueue;
        pthread_mutex_lock(&s_requestQueueMutex); //Get request task from queue
        if (pQueue->empty()) {
            pthread_mutex_unlock(&s_requestQueueMutex);
            
            if (need_quit) {
                break;
            } else {
                continue;
            }
        } else {
            if (need_quit) {
                pthread_mutex_unlock(&s_requestQueueMutex);
                break;
            }
            
            req = pQueue->front();
            pQueue->pop();
            pthread_mutex_unlock(&s_requestQueueMutex);
        }
        
        //Create a response packet and assume it will successed
        HttpResponsePacket *responsePacket = new HttpResponsePacket();
        responsePacket->request = req;
        responsePacket->succeed = true;

        //Process the request
        if (req->reqType == kHttpRequestGet) { //Get Request
            int32_t ret = processGetTask(req, writeData, &responsePacket->responseData, &responsePacket->responseCode);
            if (ret != 0) {
                responsePacket->succeed = false;
                responsePacket->responseData = errorBuffer;
            }
        } else if (req->reqType == kHttpRequestPost) { //Post Request
            int32_t ret = processPostTask(req, writeData, &responsePacket->responseData, &responsePacket->responseCode);
            if (ret != 0) {
                responsePacket->succeed = false;
                responsePacket->responseData = errorBuffer;
            }
        } else if (req->reqType == kHttpRequestDownloadFile) { //Download File Request
            bool fullyDownloaded = true;
            std::vector<std::string>::iterator iter;
            std::string saveFileName;
            std::string needDownload;
            
            for (iter = req->files.begin(); iter != req->files.end(); ++iter) {
                needDownload = *iter;
                std::string::size_type pos = needDownload.rfind("/");
                
                if (pos != std::string::npos) {
                    saveFileName = needDownload.substr(pos + 1);
                } else {
                    saveFileName = needDownload;
                }
                
                //If the download url is http://www.xxx.com/yyy.html
                //The saved file name must be yyy.html

                saveFileName = CCFileUtils::sharedFileUtils()->getWriteablePath() + saveFileName;
                CCLog(CCFileUtils::sharedFileUtils()->getWriteablePath().c_str());
                FILE *handle = fopen(saveFileName.c_str(), "w+b");
                CCLog("open file for download");
                CCLog(saveFileName.c_str());
                if (!handle) {
                    fullyDownloaded = false;
                    break;
                }
                CCLog("success");
                req->url = needDownload;
                int32_t ret = processDownloadTask(req, writeFile, handle, &responsePacket->responseCode);
                if (handle) {
                    fclose(handle);
                }
                if (ret != 0) {
                    fullyDownloaded = false;
                    break;
                }
            }
            
            //Only consider download task successfully when all the files downloaded
            if (!fullyDownloaded) {
                responsePacket->succeed = false;
                responsePacket->responseData = errorBuffer;
//.........这里部分代码省略.........
开发者ID:Siemnok,项目名称:Alarm-x4,代码行数:101,代码来源:CCHttpRequest.cpp

示例10: loadImage

static void* loadImage(void* data)
{
    // create autorelease pool for iOS
    CCThread thread;
    thread.createAutoreleasePool();

    AsyncStruct *pAsyncStruct = NULL;

    while (true)
    {
        // wait for rendering thread to ask for loading if s_pAsyncStructQueue is empty
        int semWaitRet = sem_wait(s_pSem);
        if( semWaitRet < 0 )
        {
            CCLOG( "CCTextureCache async thread semaphore error: %s\n", strerror( errno ) );
            break;
        }

        std::queue<AsyncStruct*> *pQueue = s_pAsyncStructQueue;

        pthread_mutex_lock(&s_asyncStructQueueMutex);// get async struct from queue
        if (pQueue->empty())
        {
            pthread_mutex_unlock(&s_asyncStructQueueMutex);
            if (need_quit)
                break;
            else
                continue;
        }
        else
        {
            pAsyncStruct = pQueue->front();
            pQueue->pop();
            pthread_mutex_unlock(&s_asyncStructQueueMutex);
        }        

        const char *filename = pAsyncStruct->filename.c_str();

        // compute image type
        CCImage::EImageFormat imageType = computeImageFormatType(pAsyncStruct->filename);
        if (imageType == CCImage::kFmtUnKnown)
        {
            CCLOG("unsupported format %s",filename);
            delete pAsyncStruct;
            
            continue;
        }
        
        // generate image            
        CCImage *pImage = new CCImage();
        if (! pImage->initWithImageFileThreadSafe(filename, imageType))
        {
            delete pImage;
            CCLOG("can not load %s", filename);
            continue;
        }

        // generate image info
        ImageInfo *pImageInfo = new ImageInfo();
        pImageInfo->asyncStruct = pAsyncStruct;
        pImageInfo->image = pImage;
        pImageInfo->imageType = imageType;

        // put the image info into the queue
        pthread_mutex_lock(&s_ImageInfoMutex);
        s_pImageQueue->push(pImageInfo);
        pthread_mutex_unlock(&s_ImageInfoMutex);    
    }
    
    if( s_pSem != NULL )
    {
    #if CC_ASYNC_TEXTURE_CACHE_USE_NAMED_SEMAPHORE
        sem_unlink(CC_ASYNC_TEXTURE_CACHE_SEMAPHORE);
        sem_close(s_pSem);
    #else
        sem_destroy(s_pSem);
    #endif
        s_pSem = NULL;
        delete s_pAsyncStructQueue;
        delete s_pImageQueue;
    }
    
    return 0;
}
开发者ID:haxpor,项目名称:ObjectAL-CppWrapper,代码行数:84,代码来源:CCTextureCache.cpp

示例11: installThread

static void* installThread(void* data){
    
    InstallStruct* installStruct;
    
    while (true)
    {
        // create autorelease pool for iOS
        CCThread thread;
        thread.createAutoreleasePool();
        
        std::queue<InstallStruct*> *pQueue = s_installStructQueue;
        pthread_mutex_lock(&s_installStructQueueMutex);// get async struct from queue
        if (pQueue->empty())
        {
            pthread_mutex_unlock(&s_installStructQueueMutex);
            if (need_quit) {
                break;
            }
            else {
                pthread_cond_wait(&s_SleepCondition, &s_SleepMutex);
                continue;
            }
        }
        else
        {
            installStruct = pQueue->front();
            pQueue->pop();
            pthread_mutex_unlock(&s_installStructQueueMutex);
            
            char extract[50];
            sprintf(extract, "is%sExtracted",installStruct->fileName.c_str());
            char deposit[50];
            sprintf(deposit, "is%sDeposited",installStruct->fileName.c_str());
//            bool isExtracted=S_UD->getBoolForKey(extract,false);
            bool isExtracted=false;
            if (!isExtracted) {
                CCLog("!isExtracted");
                //转存卡片资源
                bool isDeposited=false;
//                bool isDeposited=S_UD->getBoolForKey(deposit,false);
                string descFullPath=installStruct->descPath+installStruct->fileName;
                if(!isDeposited){
                    CCLog("!isDeposited");
                    if(FileUtils::depositFile(installStruct->srcFulPath,descFullPath)) {
//                        S_UD->setBoolForKey(deposit,true);
                        //                S_UD->flush();
                        CCLog("depositFile");
                    }
                }
                //解压图片资源
                if (FileUtils::unzipOpenFile(descFullPath,installStruct->descPath)) {
                    FileUtils::removeFile(descFullPath);
//                    S_UD->setBoolForKey(extract,true);
                    //            S_UD->flush();
                    CCLog("unzipOpenFile");
                }
            }
            
            pthread_mutex_lock(&s_installStructFinishedQueueMutex);
            s_installStructFinishedQueue->push(installStruct);
            pthread_mutex_unlock(&s_installStructFinishedQueueMutex);
            
            CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(ResInstall::installCallback), g_instance, 0, false);
            
        }
    }
    
    if( s_installStructQueue != NULL )
    {
        CCLog("DELETE");
        CC_SAFE_DELETE(s_installStructQueue);
        CC_SAFE_DELETE(s_installStructFinishedQueue);
        
        pthread_mutex_destroy(&s_installStructQueueMutex);
        pthread_mutex_destroy(&s_installStructFinishedQueueMutex);
        pthread_mutex_destroy(&s_SleepMutex);
        pthread_cond_destroy(&s_SleepCondition);
    }
    
    return NULL;
}
开发者ID:echenonline,项目名称:Blackcat,代码行数:81,代码来源:ResInstall.cpp

示例12: while

//Worker thread
static void *requestThread(void *data)
{
    CCThread thread;
    thread.createAutoreleasePool();
    
    HttpRequestPacket *req = NULL;
    
    while (true) {
        int semWaitRet = sem_wait(s_pSem);
        if (semWaitRet < 0) {
            CCLog("HttpRequest async thread semaphore error: %s\n", strerror(errno));
            break;
        }
        
        std::queue<HttpRequestPacket *> *pQueue = s_requestQueue;
        pthread_mutex_lock(&s_requestQueueMutex);
        if (pQueue->empty()) {
            pthread_mutex_unlock(&s_requestQueueMutex);
            
            if (need_quit) {
                break;
            } else {
                continue;
            }
        } else {
            if (need_quit) {
                pthread_mutex_unlock(&s_requestQueueMutex);
                break;
            }
            
            req = pQueue->front();
            pQueue->pop();
            pthread_mutex_unlock(&s_requestQueueMutex);
        }
        
        HttpResponsePacket *responsePacket = new HttpResponsePacket();
        responsePacket->request = req;
        responsePacket->succeed = true;

        //Process the request
        if (req->reqType == kHttpRequestGet) {
            int32_t ret = processGetTask(req, writeData, &responsePacket->responseData, &responsePacket->responseCode);
            if (ret != 0) {
                responsePacket->succeed = false;
                responsePacket->responseData = errorBuffer;
            }
        } else if (req->reqType == kHttpRequestPost) {
            int32_t ret = processPostTask(req, writeData, &responsePacket->responseData, &responsePacket->responseCode);
            if (ret != 0) {
                responsePacket->succeed = false;
                responsePacket->responseData = errorBuffer;
            }
        } else if (req->reqType == kHttpRequestDownloadFile) {
            bool fullyDownloaded = true;
            std::vector<std::string>::iterator iter;
            std::string saveFileName;
            std::string needDownload;
            
            for (iter = req->files.begin(); iter != req->files.end(); ++iter) {
                needDownload = *iter;
                std::string::size_type pos = needDownload.rfind("/");
                
                if (pos != std::string::npos) {
                    saveFileName = needDownload.substr(pos + 1);
                } else {
                    saveFileName = needDownload;
                }
                
                saveFileName = CCFileUtils::sharedFileUtils()->getWriteablePath() + saveFileName;
                FILE *handle = fopen(saveFileName.c_str(), "w+");
                if (!handle) {
                    fullyDownloaded = false;
                    break;
                }
                req->url = needDownload;
                int32_t ret = processDownloadTask(req, writeFile, handle, &responsePacket->responseCode);
                if (handle) {
                    fclose(handle);
                }
                if (ret != 0) {
                    fullyDownloaded = false;
                    break;
                }
            }
            
            if (!fullyDownloaded) {
                responsePacket->succeed = false;
                responsePacket->responseData = errorBuffer;
            }
        }
        
        pthread_mutex_lock(&s_responseQueueMutex);
        s_responseQueue->push(responsePacket);
        pthread_mutex_unlock(&s_responseQueueMutex);
    }
    
    releaseRequestQueue();
    
    if (s_pSem != NULL) {
//.........这里部分代码省略.........
开发者ID:shiren1118,项目名称:Cocos2d-x-Asynchronous-Http-Request-Library,代码行数:101,代码来源:CCHttpRequest.cpp

示例13: loadImage

static void* loadImage(void* data)
{
    AsyncStruct *pAsyncStruct = NULL;

    while (true)
    {
        // create autorelease pool for iOS
        CCThread thread;
        thread.createAutoreleasePool();
        
        // wait for rendering thread to ask for loading if s_pAsyncStructQueue is empty
        int semWaitRet = sem_wait(s_pSem);
        if( semWaitRet < 0 )
        {
            CCLOG( "CCTextureCache async thread semaphore error: %s\n", strerror( errno ) );
            break;
        }

        std::queue<AsyncStruct*>* pQueue = s_pAsyncStructQueue;

        pthread_mutex_lock(&s_asyncStructQueueMutex);// get async struct from queue
        if (pQueue->empty())
        {
            pthread_mutex_unlock(&s_asyncStructQueueMutex);
            if (need_quit)
                break;
            else
                continue;
        }
        else
        {
            pAsyncStruct = pQueue->front();
            pQueue->pop();
            pthread_mutex_unlock(&s_asyncStructQueueMutex);
        }        

        const char* filename = pAsyncStruct->filename.c_str();

        // compute image type
        CCImage::EImageFormat imageType = CCImage::computeImageFormatType(pAsyncStruct->filename);
        if (imageType == CCImage::kFmtUnKnown)
        {
            CCLOG("unsupported format %s",filename);
            delete pAsyncStruct;
            continue;
        }
        
        // generate image
        CCImage* pImage = pAsyncStruct->image;
        if (pImage && !pImage->initWithImageFileThreadSafe(filename, imageType))
        {
			pAsyncStruct->image = NULL;
            CC_SAFE_RELEASE(pImage);
            CCLOG("can not load %s", filename);
            continue;
        }
		
		unsigned char* tempData = CCImage::convertToRequiredFormat(pImage);
		if (tempData != pImage->getData())
		{
			CCSize size = CCSizeMake(pImage->getWidth(), pImage->getHeight());
			size_t bpp = pImage->getBitsPerComponent();
		CCTexture2DPixelFormat pixelFormat = pImage->hasAlpha() ? CCTexture2D::getDefaultAlphaPixelFormat() : (bpp >= 8 ? kCCTexture2DPixelFormat_RGB888 : kCCTexture2DPixelFormat_RGB565);
			pAsyncStruct->image = NULL;
			CC_SAFE_RELEASE(pImage);
			pAsyncStruct->data = tempData;
			pAsyncStruct->size = size;
			pAsyncStruct->pixelFormat = pixelFormat;
		}

        // generate image info
        ImageInfo* pImageInfo = new ImageInfo();
        pImageInfo->asyncStruct = pAsyncStruct;
        pImageInfo->imageType = imageType;

        // put the image info into the queue
        pthread_mutex_lock(&s_ImageInfoMutex);
        s_pImageQueue->push(pImageInfo);
		pthread_mutex_unlock(&s_ImageInfoMutex);
    }
    
    if( s_pSem != NULL )
    {
    #if CC_ASYNC_TEXTURE_CACHE_USE_NAMED_SEMAPHORE
        sem_unlink(CC_ASYNC_TEXTURE_CACHE_SEMAPHORE);
        sem_close(s_pSem);
    #else
        sem_destroy(s_pSem);
    #endif
        s_pSem = NULL;
        delete s_pAsyncStructQueue;
        delete s_pImageQueue;
    }

    return 0;
}
开发者ID:c0i,项目名称:Dorothy,代码行数:96,代码来源:CCTextureCache.cpp


注:本文中的CCThread类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。