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
原创粉丝点击