当前位置:   article > 正文

C++11 多线程编程_c++多线程项目

c++多线程项目
一, 创建多线程
  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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/1014176
推荐阅读
相关标签
  

闽ICP备14008679号