Simple use of c++11 multithreading Std::thread

Source: Internet
Author: User
Tags ticket

Transferred from: http://blog.csdn.net/star530/article/details/24186783

In the COCOS2DX 2.0 era, we used the Pthread library, a set of user-level line libraries, widely used in cross-platform applications. However, in COCOS2DX 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 COCOS2DX 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>

BOOLHelloworld::init () {if( !Layer::init ()) {        return false; } std::thread T1 (&helloworld::mythread, This);//Create a branch thread, callback into the Mythread functionT1.join ();//T1.detach ();Cclog ("In major thread");//in the main thread    return true;}voidHelloworld::mythread () {Cclog ("In my thread");}

Running results such as:

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 ();

The results of the operation are as follows:

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.

BOOLHelloworld::init () {if( !Layer::init ()) {        return false; } std::thread T1 (&helloworld::mythread, This,Ten, -);//Create a branch thread, callback into the Mythread functionT1.join ();//T1.detach ();Cclog ("In major thread");//in the main thread    return true;}voidHelloworld::mythread (intFirstintsecond) {Cclog ("In my thread,first =%d,second =%d", First,second);}

Output results such as:

Instance:

1. Ticket Xinxin Sun The teacher's C + + and Java multi-threaded ticketing has always kept me thinking (well, I admit I have not seen), here with cocos2d-x3.0 and c++11 Std::thread realize a bar. A total of 100 Noah's Ark ferry tickets, there are 2 ticket points A and b at the ticket ($ 10 billion for a ticket), pawn ticket sold out on the end. We know that when the program starts the process it will create a main thread, so you 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, the code is as follows:

//HelloWorld.hclassHelloWorld: Publiccocos2d::layer{ Public:    Staticcocos2d::scene*Createscene (); Virtual BOOLinit ();    Create_func (HelloWorld); voidMythreada ();//Thread A    voidMYTHREADB ();//thread B    intTickets;//Number of votes};//. cppBOOLHelloworld::init () {if( !Layer::init ()) {        return false; } Tickets= -;//100 TicketsStd::thread TA (&helloworld::mythreada, This);//Create a branch thread, callback into the Mythread functionStd::thread TB (&AMP;HELLOWORLD::MYTHREADB, This);    Ta.detach (); Tb.detach ();//T1.detach ();Cclog ("In major thread");//in the main thread    return true;}voidHelloworld::mythreada () { while(true)      {          if(tickets>0) {Sleep (Ten); Cclog ("A Sell%d", tickets--);//output ticketing, minus 1 per time        }          Else {               Break; }      }  }voidhelloworld::mythreadb () { while(true)      {          if(tickets>0) {Sleep (Ten); Cclog ("B Sell%d", tickets--); }          Else           {               Break; }      }  }

The code is simple, not much to say. We look at the output, we will find that there are a lot of popular phenomenon, because each time the results of each run is different, so the results are not posted here, which is more interesting phenomenon is the same ticket sold two times?!
The reason is not much explanation, time slice of the problem, do not understand Google. If you don't think this is going to happen, then add the following sentence before you print the result:

Sleep (+);

Operation Result:

3. 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.
3.1. Initialize the mutex lock

Std::mutex Mutex; // Thread Mutex Object

3.2, modify the code of Mythreada and MYTHREADB, add mutual exclusion lock inside

voidHelloworld::mythreada () { while(true) {Mutex.Lock();//Locking        if(tickets>0) {Sleep (Ten); Cclog ("A Sell%d", tickets--);//output ticketing, minus 1 per timeMutex.unlock ();//Unlock        }          Else{mutex.unlock ();  Break; }      }  }voidhelloworld::mythreadb () { while(true) {Mutex.Lock(); if(tickets>0) {Sleep (Ten); Cclog ("B Sell%d", tickets--);        Mutex.unlock (); }          Else{mutex.unlock ();  Break; }      }  }

The result of the operation is 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, unlock is not executed because the mutex is exclusive, so the other thread that uses this mutex lock will remain in wait state until the Threada is unlocked.

Simple use of c++11 multithreading Std::thread

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.