C++ Thread 基础使用

发布时间 2023-10-03 16:29:30作者: 王清河

C++11 Thread 使用

基础用法

  1. 头文件
  • #include<thread>
  1. 函数
  • 初始化
    • thread thread(<function_name>);
  • 线程分离
    • thread.detach();
  • 线程阻塞
    • thread.join()
  • 线程取消
    • this_thread::yield();
  • 线程休眠
    • this_thread::sleep_for(chrono::seconds(3));

代码

#include <iostream>
#include <thread>
#include <string>

using namespace std;

void proc()
{
    cout << "Sub Thread proc" << endl;
}

void proc_1(int a)
{
    cout << "Sub Thread proc 1 and a : " << a << endl;
}

void proc_2(int a, int b)
{
    string msg = "Sub Thread proc 2 and a : " + to_string(a) + " b : " + to_string(b);
    cout << msg << endl;
}

void proc_cancel()
{
    cout << "Cancel current thread" << endl;
    this_thread::yield();
}

void proc_wait_time()
{
    cout << "wait 1s to exec" << endl;
    return;
}

int main()
{
	// thread initilization
    thread thread1(proc);
    thread thread2(proc_1, 10);
    thread thread3(proc_2, 20, 30);

    cout << "Main Thread" << endl;

    // 在线程销毁前必须设置该线程是以何种方式等待线程的结束
    // 是主线程等待子线程的返回,也就是 join
    // 还是子线程运行结束后直接销毁资源,也就是 detach
# if 0
    thread1.join();
    thread2.join();
    thread3.join();
#else
    thread1.detach();
    thread2.detach();
    thread3.detach();
#endif 

    // get self id
    thread::id thread_id = this_thread::get_id();

    // sleep
    this_thread::sleep_for(chrono::seconds(3));

    // cancel thread
    thread thread4(proc_cancel);
	// thread detach
    thread4.detach();

    thread thread5(proc_wait_time);
	// thread join
    thread5.join();

    return 0;
}