多任务处理有两种形式,即:多进程和多线程。
- 基于进程的多任务处理是程序的并发执行。
- 基于线程的多任务处理是同一程序的片段的并发执行
文章目录
- 1. 多线程介绍
- 2. Windows多线程
1. 多线程介绍
每一个进程(可执行程序)都有一个主线程,这个主线程是唯一的,自动创建的,即:一个进程中只有一个主线程,自己创建的线程一般称为子线程。
join()
:等待或者阻塞,阻塞主线程的执行,直到子线程调用结束,然后子线程与主线程汇合,继续向下走。
detach()
:分离,即主线程与子线程各自执行,一旦detach(),这个主线程对象就会失去与这个主线程的关联,这个子线程就相当于被c++运行时库接管,由运行时库负责清理相关的资源。一旦调用了detach(),就不能再用join(),否则系统会报错。这是由于detach()之后,两条线程的执行速度不一致导致的。
joinable()
:判断是否可以成功使用join()或detach()的。
lock()
:使用互斥量进行共享内存保护的时候,一般情况是在所需要进行保护的代码段进行lock()操作,只有lock()成功时,代码才能继续执行,否则就会一直lock()不在向下执行,直到lock()成功。
std::lock_guard()
:类模板,直接取代lock()与unlock(),用了lock_guard()之后,就不能在使用lock()与unlock();
2. Windows多线程
Windows编写多线程C++程序需要包含头文件:#include <thread>
多线程实例:
#include <iostream>
#include <thread>
using namespace std;
void print();
void print()
{
cout << "-----------thread test-------------" << endl;
}
class test {
public:
// operator()() - 重载运算符+参数传递
void operator()() {
cout << "class subthread starting!!!" << endl;
cout << "class subthread over!!!" << endl;
}
void operator()(int x,int y) {
cout << "x+y=" << x+y << endl;
}
};
int main()
{
cout << "主线程id:" << this_thread::get_id() << endl;
// 线程休眠 - 不同的时间表示
std::this_thread::sleep_for(std::chrono::seconds(1)); //1秒 = 1000毫秒=10^6微秒
cout << "1s\n";
#if 0
std::this_thread::sleep_for(std::chrono::microseconds(2 * 1000000)); //微秒
cout << "2s\n";
std::this_thread::sleep_for(std::chrono::milliseconds(3000)); //毫秒
cout << "3s\n";
std::this_thread::sleep_for(std::chrono::minutes(1));
cout << "1min\n";
std::this_thread::sleep_for(std::chrono::hours(1));
cout << "1hour\n";
#endif
// 创建子线程
cout << "\n子线程1!!!" << endl;
thread v1(print); //入口函数print
v1.join(); //加入主线程
// 是否可joinable()
if (v1.joinable()) {
cout << "可以调用join()或者detach()" << endl;
}
else {
cout << "不可以调用join()或者detach()" << endl;
}
cout << "\n子线程2!!!" << endl;
test v2;
thread t2(v2);
t2.join();
cout << "\n子线程3!!!" << endl;
test v3;
thread t3(v3,2,4);
t3.join();
return 0;
}
运行结果如下:
以上。