C++11 多线程编程

一, 创建多线程
  1. 通过线程函数创建
#include <iostream>
#include <thread>

void func1() 
{
    std::<< cout << "this is a thread function" << std::endl;
    
    return ;
}

void func2(int a, int b) 
{
    std::cout << "a + b = " << a + b << std::endl; 

    return ;
}

int main() 
{
    std::thread th1(func1);
    if (th1.joinable()) 
    {
        th1.join();
    }
    
    std::thread th2(func2, 1, 2);
    if (th2.joinable()) 
    {
        th2.join();
    }
    
    return 0;
}
  1. Lambada表达式创建

#include <iostream>
#include <thread>

void func(int a, int b) 
{ 
    std::cout << "a + b = " << a + b << std::endl; 

    return ;
}

int main() 
{
    auto lambda = []() 
    {
        func(1, 2); 
    };
    
    std::thread th1(lambda);
    
    if (th1.joinable()) 
    {
        th1.join();
    }
    
    return 0;
}
  1. 使用类对象的成员函数
#include <iostream>
#include <memory>
#include <thread>

class funcClass 
{
    void print() 
    { 
    	std::cout << "A\n"; 
   	}
};

int main() 
{
    std::shared_ptr<funcClass > tempClass = std::make_shared<funcClass >();
    
    auto func = [&]() 
    {
    	 tempClass->print(); 
   	 };
   	 
    std::thread th1(func);
    
    if (th1.joinable()) 
    {
        th1.join();
    }
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值