目录
变形:依次用a b c三个函数打印1 2 3 4 ... ...100
进程和线程的区别
进程可以创建多个线程
线程共享的资源:代码,数据,堆
栈给线程独立分配内存
就绪、执行、阻塞
创建线程:std::thread tha(world_thread);
条件变量与互斥锁的关系
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void word_thread()
{
cout << "word_thread begin" << endl;
std::unique_lock<std::mutex> lock(mtx);//(持有)获得锁 //mtx.lock();
while (!ready)
{
//用if(!ready)可能出出现虚假唤醒?
//解决用while(!reaady){}
cout<<"ready==false" << endl;
cv.wait(lock);//主动进入条件队列
//lock持有的锁释放->unlock
//当前线程阻塞
//等待唤醒//mtx.lock
//返回锁
}
cout << "run" << endl;
cout << "end" << endl;
}
void func()
{
cv.notify_one();//唤醒
}
int main()
{
std::thread tha (word_thread);
{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::unique_lock<std::mutex> lock(mtx);
ready = true;
//唤醒条件队列中的线程
cv.notify_one();//唤醒
}
ready = true;
tha.join();
return 0;
}
互斥锁和条件变量的应用
//目标:依次打印A、B、C
std::mutex mtx;
std::condition_variable cv;
const int n = 10;
int tag = 1;//状态变量//1:A 2:B 3:C
void funa()
{
for (int i = 0; i < n; ++i)
{
std::unique_lock<std::mutex> lock(mtx);
while (tag != 1)
{
cv.wait(lock);
}
printf("funa:A\n");
printf("%d", i);
tag = 2;
cv.notify_all();
}
}
void funb()
{
for (int i = 0; i < n; ++i)
{
std::unique_lock<std::mutex> lock(mtx);
while (tag != 2)
{
cv.wait(lock);
}
printf("funa:B\n");
tag = 3;
printf("%d", i);
cv.notify_all();
}
}
void func()
{
for (int i = 0; i < n; ++i)
{
std::unique_lock<std::mutex> lock(mtx);
while (tag != 3)
{
cv.wait(lock);
}
printf("funa:C\n");
printf("%d", i);
tag = 1;
cv.notify_all();
}
}
int main()
{
std::thread tha(funa);
std::thread thb(funb);
std::thread thc(func);
tha.join();
thb.join();
thc.join();
return 0;
}
变形:依次用a b c三个函数打印1 2 3 4 ... ...100
std::mutex mtx;
std::condition_variable cv;
const int n = 10;
int tag = 1;//状态变量//1:A 2:B 3:C
int k = 1;
void funa()
{
while (k<=100)
{
std::unique_lock<std::mutex> lock(mtx);
while (tag != 1)
{
cv.wait(lock);
}
if (k <= 100)
printf("funa:%d\n",k);
k++;
tag = 2;
cv.notify_all();
}
}
void funb()
{
while(k<=100)
{
std::unique_lock<std::mutex> lock(mtx);
while (tag != 2)
{
cv.wait(lock);
}
if (k <= 100)
printf("funb:%d\n",k);
k++;
tag = 3;
cv.notify_all();
}
}
void func()
{
while(k<=100)
{
std::unique_lock<std::mutex> lock(mtx);
while (tag != 3)
{
cv.wait(lock);
}
if(k<=100)
printf("func:%d\n",k);
k++;
tag = 1;
cv.notify_all();
}
}
int main()
{
std::thread tha(funa);
std::thread thb(funb);
std::thread thc(func);
tha.join();
thb.join();
thc.join();
return 0;
}