[Cocos2d-x game engine development notes (23)] multithreading and thread synchronization

Source: Internet
Author: User
Tags usleep

Original article, reproduced please indicate the source: http://blog.csdn.net/zhy_cheng/article/details/9116479

The cocos2d-x engine implements a huge internal main loop, updating the interface between each frame, if the time-consuming operation is put into the main thread, the game interface will be card, this is intolerable, the most basic condition for a game is smoothness, Which is why C ++ is used for game development. In addition, dual-core mobile phones and quad-core mobile phones are becoming more and more common. It is time to use multithreading to tap the potential of hardware.

1. Establish the environment

Multithreading in cocos2d-x can be achieved using pthread across platforms, and it is not very difficult to understand. To use pthread, configure the project first. Right-click the project -----> properties -----> Configuration properties ----> linker -----> input ----> Add pthreadvce2.lib to the additional dependency, as shown in figure


Add the include directory, right-click the project, and choose Properties -----> C/C ++ ----> General -----> Add the include directory to the directory where the pthread header file is located.


In this way, the environment is set up.

2. Multithreading

The most important function to use pthread to implement multithreading is

Ptw32_dllport int ptw32_cdecl pthread_create (pthread_t * tid, // The thread ID const pthread_attr_t * ATTR, // The Void * (* Start) (void *) of the Creation thread *), // void * Arg pointer of the entry function); // data passed to the thread

In the helloworldscene. h file

pthread_t pidrun,pidgo;static void* th_run(void *r);static void* th_go(void *r);

Defines two functions and two threads.

Then a custom class is defined for passing data to the thread. Student class:

#pragma once#include <string>class Student{public:Student(void);Student(std::string name,int age,std::string sex);~Student(void);std::string name;int age;std::string sex;};

The source file is as follows:

#include "Student.h"#include "cocos2d.h"Student::Student(void){}Student::~Student(void){cocos2d::CCLog("delete data");}Student::Student(std::string name,int age,std::string sex){this->name=name;this->age=age;this->sex=sex;}

Start two threads in the callback function of the exit menu:

Void helloworld: menuclosecallback (ccobject * psender) {student * temp = new student (STD: string ("zhycheng"), 23, STD :: string ("male"); pthread_mutex_init (& mutex, null); pthread_create (& pidrun, null, th_run, temp); // start thread pthread_create (& pidgo, null, th_go, 0 );}

We can see that the pointer of student is passed to the pidrun thread, so the student information obtained in the pidrun thread is as follows:

        Student *s=(Student*)(r);CCLog("name is %s,and age is %d,sex is %s",s->name.c_str(),s->age,s->sex.c_str());delete s;

3. Thread Synchronization

When a thread is used, the thread synchronization must be taken into account. If different threads access resources at the same time, the access sequence is unpredictable and unpredictable results may occur.

Here we use pthread_mutex_t for synchronization. Here I will demonstrate how to use multithreading to implement the ticketing system. When selling a ticket, the ticket is sold in multiple windows at the same time. Do not sell the ticket twice, but do not sell the ticket once.

To sell tickets in the thread functions th_run and th_go, the number of tickets is a global variable. Each time one ticket is sold, the number of tickets is reduced by one. The synchronized pthread_mutex_t is also a global variable, which is used for thread synchronization.

void* HelloWorld::th_run(void *r){Student *s=(Student*)(r);CCLog("name is %s,and age is %d,sex is %s",s->name.c_str(),s->age,s->sex.c_str());delete s;while(true){pthread_mutex_lock(&mutex);if(ticket>0){CCLog("thread run sell %d",ticket);ticket--;pthread_mutex_unlock(&mutex);}else{pthread_mutex_unlock(&mutex);break;}Sleep(1);//Usleep(10);}return NULL;}

void* HelloWorld::th_go(void *r){while(true){pthread_mutex_lock(&mutex);if(ticket>0){CCLog("thread go sell %d",ticket);ticket--;pthread_mutex_unlock(&mutex);}else{pthread_mutex_unlock(&mutex);break;}Sleep(1);}return NULL;}

After mutex is locked, if other threads want to lock mutex again, they must wait. After the thread releases mutex, other threads can lock the mutex. The sleep () function can sleep the thread in milliseconds. The result of Ticket Selling is as follows:

name is zhycheng,and age is 23,sex is maledelete datathread run sell 100thread run sell 99thread go sell 98thread go sell 97thread run sell 96thread go sell 95thread go sell 94thread run sell 93thread go sell 92thread run sell 91thread go sell 90thread go sell 89thread run sell 88thread go sell 87thread run sell 86thread go sell 85thread run sell 84thread go sell 83thread run sell 82thread go sell 81thread run sell 80thread go sell 79thread run sell 78thread go sell 77thread run sell 76thread go sell 75thread run sell 74thread go sell 73thread run sell 72thread go sell 71thread run sell 70thread go sell 69thread go sell 68thread run sell 67thread go sell 66thread run sell 65thread go sell 64thread run sell 63thread go sell 62thread run sell 61thread go sell 60thread run sell 59thread go sell 58thread run sell 57thread go sell 56thread run sell 55thread go sell 54thread run sell 53thread run sell 52thread go sell 51thread run sell 50thread go sell 49thread run sell 48thread go sell 47thread run sell 46thread go sell 45thread run sell 44thread run sell 43thread go sell 42thread run sell 41thread run sell 40thread go sell 39thread run sell 38thread run sell 37thread run sell 36thread run sell 35thread go sell 34thread run sell 33thread run sell 32thread go sell 31thread run sell 30thread run sell 29thread run sell 28thread run sell 27thread run sell 26thread run sell 25thread go sell 24thread run sell 23thread go sell 22thread go sell 21thread run sell 20thread go sell 19thread run sell 18thread run sell 17thread go sell 16thread run sell 15thread go sell 14thread go sell 13thread run sell 12thread go sell 11thread go sell 10thread run sell 9thread go sell 8thread run sell 7thread go sell 6thread go sell 5thread run sell 4thread go sell 3thread run sell 2thread run sell 1

The printed result is correct. What is the result if mutex is not added? I comment out the mutex synchronized by the thread and the output result is:

name is zhycheng,and age is 23,sex is maledelete datathread run sell 100thread run sell 99thread run sell 98thread go sell 97thread run sell 96thread go sell 95thread run sell 94thread go sell 94thread run sell 92thread run sell 91thread go sell 90thread run sell 89thread go sell 88thread run sell 87thread run sell 86thread go sell 86thread go sell 84thread run sell 83thread go sell 82thread run sell 81thread go sell 80thread run sell 79thread run sell 78thread go sell 77thread run sell 76thread run sell 75thread go sell 74thread run sell 73thread go sell 72thread run sell 71thread go sell 70thread go sell 69thread run sell 68thread go sell 67thread go sell 66thread run sell 65thread go sell 64thread go sell 63thread run sell 62thread go sell 61thread run sell 60thread run sell 59thread run sell 58thread run sell 57thread run sell 56thread run sell 55thread go sell 54thread run sell 54thread go sell 52thread run sell 52thread go sell 50thread run sell 50thread go sell 49thread run sell 47thread go sell 47thread go sell 45thread run sell 45thread run sell 43thread go sell 43thread run sell 41thread go sell 41thread go sell 39thread run sell 39thread run sell 37thread go sell 37thread go sell 35thread run sell 35thread go sell 33thread run sell 33thread go sell 31thread run sell 31thread go sell 29thread run sell 29thread go sell 27thread run sell 27thread go sell 25thread run sell 25thread run sell 23thread go sell 23thread run sell 21thread go sell 21thread go sell 19thread run sell 19thread run sell 17thread go sell 17thread go sell 15thread run sell 15thread run sell 13thread go sell 13thread run sell 11thread go sell 11thread go sell 9thread run sell 9thread run sell 7thread go sell 7thread go sell 5thread run sell 5thread go sell 3thread run sell 3thread go sell 1thread run sell 1

We can see that some tickets are sold twice, and some are not sold.

4. Note

1. The sleep () function is used to sleep a thread. This function is not cross-platform and can be used only on Windows. usleep is used on other platforms.

2. Do not use cocos2d-x to manage memory in a non-main threadCCObject::retain(),CCObject::release()ByCcobject: autorelease (), because ccautoreleasepool is NOT thread-safe, OpenGL context is not thread-safe, so do not use cocos2d-x APIs and UI operations in the main thread.

Download the source code of the final project: http://download.csdn.net/detail/zhy_cheng/5600979

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.