cocos2d-x3.2 下使用多线程

本文提供了在Cocos2dx中使用C++进行多线程编程的三个示例,包括创建单个线程、批量创建多个线程以及使用互斥锁实现线程同步的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

事实上在cocos2dx下使用多线程事实上就是用C++去写,这里提供几个简单的样例:

原文地址:http://blog.youkuaiyun.com/qqmcy/article/details/36227377

1、

//
//  PublicScene.cpp
//  testthirdone
//
//  Created by 杜甲 on 14-7-1.
//


void hello()
{
    log("hello thread");
}

bool PublicScene::init()
{
    bool bRet = false;
    do {
        CC_BREAK_IF(!Scene::init());
		
		
        std::thread t1(hello);
        t1.join();
        log("主线程");
		
		
		  bRet = true;
	  } while (0);
	  return bRet;
}



        std::thread t1(hello);
        t1.join();
        log("主线程");

2、

//
//  PublicScene.cpp
//  testthirdone
//
//  Created by 杜甲 on 14-7-1.
//
//

void hello()
{
    log("hello thread");
}

bool PublicScene::init()
{
    bool bRet = false;
    do {
        CC_BREAK_IF(!Scene::init());
		
		
        std::vector<std::thread> threads;
        for (int i = 0; i < 5; ++i)
        {
            threads.push_back(std::thread([ = ]()
            {
                log("%s",StringUtils::format(" thread %d",i).c_str());
            }));
        }
        
        for (auto& thread :threads) {
            thread.join();
        }
        
        log("Main Thread");

		
		
		  bRet = true;
	  } while (0);
	  return bRet;
}

3、

//
//  PublicScene.cpp
//  testthirdone
//
//  Created by 杜甲 on 14-7-1.
//
//

void hello()
{
    log("hello thread");
}

bool PublicScene::init()
{
    bool bRet = false;
    do {
        CC_BREAK_IF(!Scene::init());
		
		
        std::mutex m;
        std::thread t1([&m](){
            m.lock();
            for (int i = 0; i < 10; i++) {
                
                log("%s",StringUtils::format(" thread1 %d",i).c_str());

               
            }
             m.unlock();
        });
        
        
        std::thread t2([&m](){
        
            m.lock();
            for (int i = 0; i < 10; i++) {
                
                
                log("%s",StringUtils::format(" thread2 %d",i).c_str());
                

               
            }
             m.unlock();
        });
        
        t1.join();
        t2.join();
        
        log("Main Thread");
		
		
		  bRet = true;
	  } while (0);
	  return bRet;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值