C++11_多线程std::thread的使用
来源:互联网 发布:mac桌面显示时间 编辑:程序博客网 时间:2024/06/15 07:26
#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"#include "cocos-ext.h"#include <thread>#include <mutex>USING_NS_CC;USING_NS_CC_EXT;class HelloWorld : public cocos2d::CCLayer{public: virtual bool init(); static cocos2d::CCScene* scene(); CREATE_FUNC(HelloWorld);void myThread();void myThread(int first, int second);void myThreadA();void myThreadB();int tickets;std::mutex mutex;};#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"#include <iostream>#include <string>using namespace std;USING_NS_CC;CCScene* HelloWorld::scene(){ CCScene *scene = CCScene::create(); HelloWorld *layer = HelloWorld::create(); scene->addChild(layer); return scene;}bool HelloWorld::init(){ if ( !CCLayer::init() ) { return false; } CCSize winSize = CCDirector::sharedDirector()->getWinSize();tickets = 100;// 第一种创建多线程(没有传参)std::thread t1(&HelloWorld::myThread, this); // 创建一个分支线程,回调到myThread线程里面t1.join(); // 等待子线程myThread执行完之后,主线程才可以继续执行下去,此时主线程会释放掉执行完后的子线程资源//t1.detach(); // 如果不想等待子线程,可以在主线程里面执行t1.detach()将子线程从主线程里分离,子线程执行完成后会自己释放掉资源。分离后的线程,主线程将对它没有控制权了// 第二种创建多线程(传入参数)std::thread t1(&HelloWorld::myThread, this, 10, 20);t1.join();//t1.detach();std::thread tA(&HelloWorld::myThreadA, this);std::thread tB(&HelloWorld::myThreadB, this);tA.detach();tB.detach();CCLOG("in main thread!"); // 在主线程里面 return true;}void HelloWorld::myThread(){CCLOG("in my thread!"); // 在分支线程里面}void HelloWorld::myThread(int first, int second){CCLOG("first is %d, second is %d", first, second);}void HelloWorld::myThreadA(){while (true){mutex.lock(); //加锁if (tickets > 0){//Sleep(10);CCLOG("A Sell %d\n", tickets--); //输出售票,每次减1mutex.unlock(); // 解锁}else {mutex.unlock();break;}}}void HelloWorld::myThreadB(){while (true){mutex.lock(); //加锁if (tickets > 0){//Sleep(10);CCLOG("B Sell %d\n", tickets--);mutex.unlock(); // 解锁}else{mutex.unlock();break;}}}
0 1
- C++11_多线程std::thread的使用
- C++11多线程std::thread的简单使用(上)
- C++11 多线程学习----std::thread类的简单使用
- 一、C++11多线程std::thread的简单使用(上)
- 二、C++11多线程std::thread的简单使用(下)
- C++11多线程std::thread的简单使用
- 一、C++11多线程std::thread的简单使用(上)
- 二、C++11多线程std::thread的简单使用(下)
- C++11多线程std::thread的简单使用
- C++11多线程std::thread的简单使用
- C++11多线程std::thread的简单使用
- 多线程std::thread的使用 以及performFunctionInCocosThread函数
- 使用C++11进行多线程归并排序:std::thread
- Cocos2dx 3.0 过渡篇(二十六)C++11多线程std::thread的简单使用(上)
- Cocos2dx 3.0 过渡篇(二十七)C++11多线程std::thread的简单使用(下)
- Cocos2dx 3.0 过渡篇(二十六)C++11多线程std::thread的简单使用(上)
- Cocos2dx 3.0 过渡篇(二十七)C++11多线程std::thread的简单使用(下)
- 【Cocos2d-x 3.0】C++11多线程std::thread的简单使用
- EditView控件
- Android开发贴士集合
- 编解码学习笔记(一):基本概念
- jdom 使用api
- Robotium中文API(13)-solo.clickOnCheckBox
- C++11_多线程std::thread的使用
- Android 中自定义View的应用.
- linux select函数用法
- Robotium中文API(14)-solo.clickOnEditText
- cocos2dx之抽奖界面与获奖概率的设计(一)
- Mavn的web项目运行Main函数
- 教你如何做决策--运筹学的初识
- Android文件查看与读取(一)
- 新手学EasyUi+JS----ComboBox 级联