COCOS2DX 3.0 Transition Chapter (27) C++11 multithreading Std::thread simple use (bottom)

Source: Internet
Author: User
Tags mutex ticket

This article continues to say: last portal : http://blog.csdn.net/star530/article/details/24186783

The simple thing I say almost the same, want to dig a bit deep almost put oneself to fill in.

Here is a practical walkthrough. Please agree to my visit occasionally e past a thread of the blog, he used the pthread. I'm going to use std::thread here.


1. Ticketing
Xinxin Sun Teacher's C + + and Java multi-threaded ticketing has always kept me thinking (well, I admit I haven't seen it). Here with the cocos2d-x3.0 and c++11 Std::thread to achieve a bar. Total co-owned 100 Noah's Ark ferry tickets. There are 2 ticket points A and b at the ticket ($ 10 billion for one ticket). Pawn ticket sold out and finished. We know that when a program starts the process, it creates a main thread, so it can create 2 threads A and B on the main thread, then the threads A and B are sold separately, and the pawn ticket number is 0, ending threads A and B.


2. Multi-threaded ticketing, code such as the following:

Helloworld.hclass helloworld:public cocos2d::layer{public:static cocos2d::scene* createScene ();          virtual BOOL init (); Create_func (HelloWorld); void Mythreada ();//thread avoid mythreadb ();//Thread bint tickets;//votes};//.cppbool Helloworld::init ( ) {if (!    Layer::init ()) {return false; }tickets = 100;//100 ticket std::thread tA (&helloworld::mythreada,this);//Create a branch thread, callback into the Mythread function Std::thread TB ( &helloworld::mythreadb,this); Ta.detach (); Tb.detach ();//t1.detach (); Cclog ("in major thread");//return True on the main thread;}            void Helloworld::mythreada () {while (true) {if (tickets>0) {Sleep (10); Cclog ("A Sell%d", tickets--);//Output ticketing.          Minus 1} else {break;            }}}void helloworld::mythreadb () {while (true) {if (tickets>0) {Sleep (10);          Cclog ("B Sell%d", tickets--);          } else {break; }      }  }

The code is very easy. Not much to say. Let's take a look at the output. Will find a lot of popular phenomenon. Because each person executes a different result each time. So the results are not posted here, The more interesting phenomenon is that the same ticket sold two times?!
The reason is not much explained, time slice of the problem, unclear Google's.

Assuming you don't think that's the case, then add the following sentence before you print the result:

Sleep (100);
The results of the execution see:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvc3rhcjuzma==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "/>

3. Synchronizing data with mutually exclusive objects
This problem is mainly due to the execution of a thread halfway, the time slice of the switch caused another thread to change the same data, when the original thread again and continue to execute, the data due to the changes caused by the result error.

So all we have to do is make sure that this thread is completely executed. So the line Cheng is a good note, mutually exclusive object mutex is this lock.
3.1. Initialize mutually exclusive lock

Std::mutex mutex;//threads mutually exclusive objects
3.2, change Mythreada and MYTHREADB code, in the inside to join mutually exclusive lock

void Helloworld::mythreada () {while (true)      {  mutex.lock ();//Locking        if (tickets>0)          {  Sleep];            Cclog ("A Sell%d", tickets--);//Output ticketing. Minus 1  mutex.unlock ();//Unlock        }          else {  mutex.unlock ();            Break;}}}  void Helloworld::mythreadb () {while (true)      {  mutex.lock ();        if (tickets>0)          {  Sleep (ten);            Cclog ("B Sell%d", tickets--);  Mutex.unlock ();        }          else           {  mutex.unlock ();            Break;}}}  
The results of the execution are as follows. Perfect

There is one thing to note about using Std::mutex: Std::mutex using member functions in thread a lock locking unlock unlock, it seems to work very well, but this is not safe, you have to always remember that lock must be unlock. However, if there is an exception between them or if the thread exits directly, the unlock is not executed, because this mutual repulsion is exclusive. So before the Threada is unlocked, other threads that use this mutually exclusive lock will remain in the waiting state and are not executed .

Well, just write it down here.

Hey, hey.

Respect original, reprint please indicate source: http://blog.csdn.net/star530/article/details/24187103

COCOS2DX 3.0 Transition Chapter (27) C++11 multithreading Std::thread simple use (bottom)

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.