多线程基础
第一个线程示例
- thread 头文件在 C++11 版本开始支持.linux 下需要导入 pthread 库.
#include <thread>
#include <iostream>
//Linux -lpthread
using namespace std;
void ThreadMain()
{
// 打印主线程 ID
cout << "begin sub thread main " << this_thread::get_id() << endl;
for (int i = 0; i < 10; i++)
{
cout << "in thread " << i << endl;
// 延时 1000ms
this_thread::sleep_for(chrono::seconds(1));
}
// 打印子线程 ID
cout << "end sub thread main " << this_thread::get_id() << endl;
}
int main(int argc, char* argv[])
{
// 主线程
cout << "main thread ID " << this_thread::get_id() << endl;
// 子线程创建启动
thread th(ThreadMain);
cout << "begin wait sub thread "<< endl;
// 主线程等待 th 线程执行完毕
th.join();
// th 线程执行完毕后,主线程继续执行下面的代码.
cout << "end wait sub thread " << endl;
return 0;
}
第二个线程示例
- join() 函数是一个等待线程完成函数,主线程需要等待子线程运行结束了才可以结束
- detach() 函数是子线程的分离函数,当调用该函数后, 该线程称为分离线程, 线程被分离到后台运行, 主线程不需要等待该线程结束才结束.
#include <thread>
#include <iostream>
//Linux -lpthread
using namespace std;
bool is_exit = false;
void ThreadMain()
{
cout << "begin sub thread main " << this_thread::get_id() << endl;
for (int i = 0; i < 10; i++)
{
if (!is_exit) break;
cout << "in thread " << i << endl;
// 延时 1000ms
this_thread::sleep_for(chrono::seconds(1));
}
cout << "end sub thread main " << this_thread::get_id() << endl;
}
int main(int argc, char* argv[])
{
{
// 崩溃,thread 的引用对象大括号作用域外被销毁,子线程还在运行.
// thread th(ThreadMain);
}
{
thread th(ThreadMain);
// 子线程与主线程分离,守护线程
//坑: 主线程退出后,子线程不一定退出
th.detach();
}
{
thread th(ThreadMain);
// 延时 1000ms
this_thread::sleep_for(chrono::seconds(1));
// 通知子线程退出
is_exit = true;
cout << "主线程阻塞,等待子线程退出" << endl;
// 主线程阻塞,等待子线程退出
th.join();
cout << "子线程已经退出!" << endl;
}
// 保证主线程没有退出.
getchar();
return 0;
}