The basic realization of multithreading in Cocos2d-x 3.x

Source: Internet
Author: User

is currently rewriting a small game based on the early Cocos2d-x 2.x implementation, when it comes to multithreaded code, suddenly the compiler prompts to find no header file pthread.h. Checked, found that today's 3.x is no longer supported pthread.h header files, the previous 2.X era this file is contained in $ (ProjectDir). \.. The \cocos2dx\platform\third_party\win32\pthread path.

It is now recommended to use the Std::thread-related API directly in 3.X, which is, of course, a multithreaded API after simplified processing of C + + 11.

The overall use of ideas summarized as follows:


--------------------------------------------------------------------------------

In the Cocos2d-x 2.0 era, we used the Pthread library, a set of user-level line libraries, widely used in cross-platform applications. However, in Cocos2d-x 3.0 did not find a pthread support files, the original c++11 already has a better use for threading operations of the class Std::thread. The version of Cocos2d-x 3.0 defaults to the vs2012 version, which supports the new features of c++11, and it is simply convenient to use Std::thread to create threads.

The following is a brief introduction to the following Std::thread, the code needs to include the header file <thread>.

bool helloworld::init ()    {        if  ( ! Layer::init ()  )        {            return false;       }                std::thread t1 (&HelloWorld:: Mythread,this);//create sub-range, callback to MyThread function        t1.join ();    //   t1.detach ();            cclog ("In major  thread ");//In the main thread            return true;    }       void helloworld::mythread ()    {        cclog ("In my thread");    } 

--------------------------------------------------------------------------------

Explain

T.join () waits for the mythread of the child thread to execute, the main thread can continue execution, and the main thread frees the child thread resources after execution. As can be seen from the above picture, it is the first output "in my thread", and then output "in major thread".

Of course, if you do not want to wait for a child thread, you can execute T1.detach () inside the main thread to detach the child thread from the main thread, and the child thread will release the resource itself when it finishes executing. The main thread will have no control over the disconnected threads. As follows:

Std::thread T1 (&helloworld::mythread,this);//Create a branch thread, callback into the MyThread function
T1.detach ();
--------------------------------------------------------------------------------

Of course, you can also wear parameters to the thread function, where bind is used. In the following example, when instantiating a threading object, the thread function Mythread followed by two parameters.

Bool helloworld::init ()        {            if  ( ! Layer::init ()  )            {                return false;            }           &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;STD::THREAD&NBSP;T1 (& HELLOWORLD::MYTHREAD,THIS,10,20);//Create a branch thread, callback into the MyThread function             t1.join ();        //  t1.detach ();                             cclog ("In major thread");//In the main thread             return true;       }                         void helloworld::mythread (Int first,int second)         {           cclog ("In my  thread,first = %d,second = %d ", First,second);        }

--------------------------------------------------------------------------------

Synchronizing data with Mutex objects

The problem is mainly because when one thread executes halfway, the switch of the time slice causes the other thread to modify the same data, and when the original thread is switched again and continues to run down, the data is changed and the result is faulted. So what we're going to do is make sure that this thread is fully executed, so it's a good idea to line Cheng that the mutex is the lock.

1) Initialize Mutex lock

  Std::mutex mutex;//Thread Mutex object


2) Modify the code of Mythreada and MYTHREADB, add the mutex inside

void Helloworld::mythreada ()
    {           while (True)               {                  mutex.lock ();//Locking                 if (tickets>0)                   {                      sleep (10);                     cclog ("a sell %d", tickets--);//output ticket, each minus 1                      mutex.unlock ();//Unlock                 }                  else {                      mutex.unlock ();                    break;                                       }              }      &NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;VOID&NBSP;HELLOWORLD::MYTHREADB ()         {           while ( True)              {                  mutex.lock ();                if  (tickets>0)                   {                      sleep (Ten);                    cclog ("B Sell  %d ", tickets--);                      mutex.unlock ();                }                  else                 {                       mutex.unlock ();                    break;                               }             }          }

There's a place to pay attention to using Std::mutex.

Std::mutex using member functions in thread a lock locking unlock to unlock, it seems to work very well, but it is not safe, you have to always remember that lock must be unlock, but if there is an exception between them or the thread exits directly unlock there is no execution , because this mutex is exclusive, other threads that use this mutex lock will remain in the wait state until the Threada is unlocked.


The above summary is only the basic case of implementing multithreaded programming supported by C + + 11, which is not discussed in cases involving more complex than simple mutexes.

This article is from the "Green Peak" blog, please make sure to keep this source http://zhuxianzhong.blog.51cto.com/157061/1612306

The basic realization of multithreading in Cocos2d-x 3.x

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.