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

Source: Internet
Author: User
Tags mutex ticket

Http://www.cocoachina.com/cocos/20140523/8530.html

Simple use of "Cocos2d-x 3.0" c++11 multithreaded Std::thread2014-05-23 17:01 Edit: Wupeng Category: Cocos engine Source: Cocoachina 08773

Cocos2d-x v3.0 Multithreading c++11

Recruitment information:
    • Cocos2d-x front-end main thread
    • iOS Development engineer of Hangzhou NetEase
    • Senior Java Engineer
    • IOS Creative Engineer
    • Find an iOS siege lion
    • iOS Senior Development Engineer
    • Advanced iOS Development Engineer
    • Mobile internet company-ios Senior Engineer
    • iOS Development Engineer
    • iOS Development Engineer
    • iOS Advanced Development Engineer (quick strokes)

The blog from Tianya Horizon

This article is about threading! 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 supporting documents, the original C++11 already has a better class for threading operations 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. Here is a brief introduction to the following Std::thread, code need to include header files
  1. BOOL Helloworld::init ()
  2. {
  3. if (! Layer::init ())
  4. {
  5. return false;
  6. }
  7. Std::thread T1 (&helloworld::mythread, this); Create a branch thread, callback into the Mythread function
  8. T1.join ();
  9. T1.detach ();
  10. Cclog ("in major thread"); In the main thread
  11. return true;
  12. }
  13. void Helloworld::mythread ()
  14. {
  15. Cclog ("in my Thread");
  16. }
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:
    1. Std::thread T1 (&helloworld::mythread, this); Create a branch thread, callback into the Mythread function
    2. T1.detach ();
The results of the operation are as follows: Of course, you can also wear parameters to the thread function, which is used here. Bind。 In the following example, when instantiating a threading object, the thread function Mythread followed by two parameters.
  1. BOOL Helloworld::init ()
  2. {
  3. if (! Layer::init ())
  4. {
  5. return false;
  6. }
  7. Std::thread T1 (&helloworld::mythread,this,10,20); Create a branch thread, callback into the Mythread function
  8. T1.join ();
  9. T1.detach ();
  10. Cclog ("in major thread"); In the main thread
  11. return true;
  12. }
  13. void Helloworld::mythread (int First,int second)
  14. {
  15. Cclog ("in my thread,first =%d,second =%d", first,second);
  16. }
Output results such as: simple things I have said almost, the following practical walkthrough. Please allow me to refer to the occasional e-story of a thread of the blog, he used pthread, here I use Std::thread. TicketingA 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. This is accomplished with the std::thread of cocos2d-x3.0 and c++11. multi-thread ticketing, the code is as follows:
  1. HelloWorld.h
  2. Class HelloWorld: Public cocos2d::layer
  3. {
  4. Public
  5. static cocos2d::scene* createscene ();
  6. virtual BOOL init ();
  7. Create_func (HelloWorld);
  8. void Mythreada (); //Thread a
  9. void mythreadb (); //thread B
  10. int tickets; //Number of votes
  11. };
  12. . cpp
  13. BOOL Helloworld::init ()
  14. {
  15. if (! Layer::init ())
  16. {
  17. return false;
  18. }
  19. Tickets = 100; //100 Tickets
  20. Std::thread TA (&helloworld::mythreada, this); Create a branch thread, callback into the Mythread function
  21. Std::thread TB (&helloworld::mythreadb, this);
  22. Ta.detach ();
  23. Tb.detach ();
  24. T1.detach ();
  25. Cclog ("in major thread"); In the main thread
  26. return true;
  27. }
  28. void Helloworld::mythreada ()
  29. {
  30. While (true)
  31. {
  32. if (tickets>0)
  33. {
  34. Sleep (10);
  35. Cclog ("A Sell%d", tickets--); Output ticketing, minus 1 per time
  36. }
  37. else {
  38. Break ;
  39. }
  40. }
  41. }
  42. void Helloworld::mythreadb ()
  43. {
  44. While (true)
  45. {
  46. if (tickets>0)
  47. {
  48. Sleep (10);
  49. Cclog ("B Sell%d", tickets--);
  50. }
  51. Else
  52. {
  53. Break ;
  54. }
  55. }
  56. }
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:
    1. Sleep (100);
Operation Result: synchronizing data with mutex objectsThe 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
    1. Std::mutex Mutex; //Thread Mutex object
2) Modify the code of Mythreada and MYTHREADB, add the mutex inside
  1. void Helloworld::mythreada ()
  2. {
  3. While (true)
  4. {
  5. Mutex.lock (); //Locking
  6. if (tickets>0)
  7. {
  8. Sleep (10);
  9. Cclog ("A Sell%d", tickets--); Output ticketing, minus 1 per time
  10. Mutex.unlock (); //Unlock
  11. }
  12. else {
  13. Mutex.unlock ();
  14. Break ;
  15. }
  16. }
  17. }
  18. void Helloworld::mythreadb ()
  19. {
  20. While (true)
  21. {
  22. Mutex.lock ();
  23. if (tickets>0)
  24. {
  25. Sleep (10);
  26. Cclog ("B Sell%d", tickets--);
  27. Mutex.unlock ();
  28. }
  29. Else
  30. {
  31. Mutex.unlock ();
  32. Break ;
  33. }
  34. }
  35. }
Run the result as follows, perfect!

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.