茄子的个人空间

C++多线程编程

字数统计: 543阅读时长: 2 min
2021/12/10
loading

常用线程函数

  • join() :

    阻塞主线程,让主线程等待子线程执行完,当子线程执行完毕,这个join()就执行完毕,主线程继续执行

  • detach() :

    从主线程中将子线程分离,主线程不必等待子线程执行完,一旦detach()之后子线程将失去与主线程的关联,
    此时这个子线程就会驻留在后台运行,被c++运行时接管,当这个子线程执行完成后,由运行时库负责清理线程相关的资源。

线程创建方法

  • 通过函数创建线程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #include <iostream>
    #include <thread>
    using namespace std;
    void do_something(){
    cout << "线程开始"<< endl;
    //do something
    cout << "线程结束" << endl;
    }
    int main(){
    thread myjob (do_something);
    myjob.join(); //阻塞主线程,等待子线程结束
    cout << "The End" <<endl;
    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
    34
    #include <iostream>
    #include <thread>
    using namespace std;

    class myClass{
    private:
    int data;
    public:
    myClass(int d):data(d){
    cout << "构造函数" <<endl;
    }
    myClass(const myClass&myClass1):data(myClass1.data){
    cout << "拷贝构造函数" <<endl;
    }
    ~myClass(){
    cout << "析构函数" <<endl;
    }
    void operator()(){
    //线程的入口
    cout << "线程开始" <<endl;
    // do something
    cout << "线程结束" << endl;
    }
    };


    int main(){
    int a = 10;
    myClass myclass(a);
    thread myjob (myclass); // 复制一次myclass
    myjob.join();
    cout << "The End" <<endl;
    return 0;
    }
  • 通过lambda表达式创建线程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #include <iostream>
    #include <thread>
    using namespace std;

    int main(){
    auto myLambdaThread = []{
    cout << "线程开始" << endl;
    // do something
    cout << "线程结束" << endl;
    };
    thread myjob (myLambdaThread);
    myjob.join();
    cout << "The End" <<endl;
    return 0;

    }

传递临时对象作为线程参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <thread>
using namespace std;
void do_something_with_parameters(const int& a, char *buff){
cout << a << endl;
cout << buff << endl;//传指针危险
}
int main(){
int val = 1;
char buff[] = "this is a test!";
thread myjob (do_something_with_parameters, val, buff);
myjob.join(); //阻塞主线程,等待子线程结束
cout << "The End" <<endl;
return 0;
}

线程id

1
2
获取线程id:get_id()
获取当前线程id:std::this_thread::get_id()

线程间的值传递

1
2
std::ref()
std::move()

最多可以使用的线程数

1
std::thread::hardware_concurrency()
CATALOG
  1. 1. 常用线程函数
  2. 2. 线程创建方法
  3. 3. 传递临时对象作为线程参数
  4. 4. 线程id
  5. 5. 线程间的值传递
  6. 6. 最多可以使用的线程数