一、多线程的状态
- 初始化 (Init):该线程正在被创建。
- 就绪 (Ready):该线程在就绪列表中,等待CPU的调度。
- 运行 (Running):该线程正在运行。
- 阻塞(Blocked):该线程被阻塞挂起。Blocked状态包括:pend(锁、事件、信号量等阻塞)、suspend(主动pend)、delay(延时阻塞)、pendtime(因为锁、事件、信号量时间等超时等待)。
- 退出(Exit):该线程运行结束,等待父线程后收其控制块资源。
二、多线程之间的竞争关系和临界区
1、竞争关系(Race condition)
多个线程同时读写共享资源
例如:
#include<iostream>
#include<thread>
#include<string>
using namespace std;
void Test()
{
cout << "---------------" << endl;
cout << "Test 1 " << endl;
cout << "Test 2 " << endl;
cout << "-----------------" << endl;
}
int main()
{
for (int i = 0; i < 10; i+&#