创建线程有多少种方式

C++多线程

C++11引入了线程类thread,头文件为
#include <thread>
创建多线程的方法:
std::thread threadName(functionName, parameter1, paramater2, …);
传递参数可以传左值,右值,引用(使用std::ref)和常引用(使用std::cref)。
例如:
std::thread threadName(functionName, leftValue, rightValue, std::ref(refArg), std::cref(constRefArg));
参数先copy或move到std::thread对象后再move给函数。

多线程的创建

  1. 普通函数
#include <iostream>
#include <thread>

void func(int a, int& b){
    a = 2;
    b = 2;
}

int main(){
    int a = 1;
    int b = 1;
    //创建子线程
    std::thread newThread(func, a, std::ref(b));
    std::cout << a << “ ” << b << std::endl;
    
    
    //主线程等待子线程结束
    newThread.join();
    
    return 0;
}

编译:
g++ main.cpp -o main -pthread

  1. 成员函数
#include <iostream>
#include <thread>

class MyClass{
public:
    void func(const int& num){
        std::cout << “I am” << num << “ years old” << std::endl;
    }
};

int main(){
    MyClass obj;
    int num = 20;
    std::thread newThread(&MyClass::func, &obj, std::cref(num));
    
    newThread.join();
    
    return 0;
}
  1. 仿函数
#include <iostream>
#include <thread>

class MyClass{
public:
    void operator() (int& num){
        std::cout << “sub-thread start” << std::endl;
        num = 30;
        std::cout << “sub-thread end” << std::endl;
    }
};

int main(){
    std::cout << “main thread start” << std::endl;
    
    MyClass obj;
    int num = 29;
    std::cout << “num= ” << num << std::endl;
    
    std::thread newThread(obj, std::ref(num));
    //也可如下实现
    //std::thread newThread(MyClass(), std::ref(num));
    
    newThread.join();
    
    std::cout << “num= ” << num << std::endl;
    std::cout << “main thread end” << std::endl;
    
    return 0;
}
  1. 匿名函数lambda
#include <iostream>
#include <thread>

int main(){
    auto function = [](int a) {std::cout << a << std::endl;}
    
    std::thread newThread(function, 10);
    //或者以下方式直接调用lambda函数,无需上述语句
    //std::thread newThread([](int a) {std::cout << a << std::endl;}, 10);
    
    newThread.join();
    
    return 0;
}
posted @ 2023-03-01 16:27  yytarget  阅读(20)  评论(0编辑  收藏  举报