1.thread库简介
C++11: CPU多核与多线程、并行与并发
https://blog.csdn.net/qq_29797957/article/details/99653795
/********************* std::Thread *************************
* #include <thread>
* #include <mutex>
*
* 主要有两个函数
* join(): 多个子线程并行执行,join函数会阻塞主流程,所以子线程都执行完成之后才继续执行主线程;
*
* detach: detach将子线程从主流程中分离,独立运行,不会阻塞主线程;
*
* 如果对函数加锁,则不管主程序如何调用,都会将加锁的线程执行完之后,才会开始下一个线程
******************************************************/
#include <thread>
#include <iostream>
// 互斥锁: 数据同步
#include <mutex>
std::mutex mu;
void run()
{ mu.lock(); // 保护每个线程完整执行
for (int i = 0; i < 10; ++i)
{
std::cout << i << std::endl;
}
mu.unlock();
}
void ThreadTest01()
{
for(int i=0; i<5; i++)
{
std::cout<<"ThreadTest01 is working !\n";
}
}
int main(int argc, char* argv[])
{
std::thread theard1(&run);
std::thread theard2(&ThreadTest01);
std::thread theard3(&run);
theard1.join();
theard2.join();
theard3.join();
for(int i=0; i<5; i++)
{
std::cout<<"Main Functions is Working !\n";
}
return 0;
}