lock_guard用法std::lock_guardstd::mutex guard(mutex2);是个局部变量,在该作用于结束后回自动解锁。而unique_lock是lock_guard的升级版。一般不用lock和unlock是因为只要在锁的范围内只要有return就会出错。
std::thread t(foo);有参数时:std::thread t(foo,1,2,“hello”);而且线程不能进行复制,拷贝,但是可以移动位置。
每个线程定义后,在结束阶段得join()进行资源回收,不然的话运行时回报错。
每个线程都有自己的栈空间。
有内存池,线程池等,池里有很多线程,需要使用时九拿来用,避免创建线程,可以重复利用。最多创建的线程数是看你的cpu的核心数,如4核心cpu就导致线程池最多8个线程。
条件变量:可以做到对线程的阻塞,让其他线程先完成。
头文件#include<condition_variable>
定义方法std::condition_variable cond_var;
阻塞方法cond_var.wait(lock, [] { return cap == 0; }); (第一个lock不用改是表示上锁了,第二个lambda是表示cap==0时阻碍结束。
cond_var.notify_one(); 表示唤醒其他的一个进程但不知到时哪个进程,只有两个进程时很好用。
cond_var.notify_all(); 唤醒其他所有的进程。
课内作业:下载资源和播放资源,下载时候不能播放,下载到10时可以进行播放,每次播放5个资源,资源播放完了继续下载
#include
#include
#include
#include<windows.h>
#include<condition_variable>
const int cap_max = 10;
int cap = 0;
std::mutex mtx;
std::condition_variable cond_var;
void download()
{
std::unique_lockstd::mutex lock(mtx);
std::cout << “Download Start” << std::endl;
while (cap < cap_max) {
Sleep(500);
cap++;
std::cout << "已下载: " << cap << std::endl;
if (cap == cap_max) {
std::cout << “File download ready!” << std::endl;
cond_var.notify_one();
cond_var.wait(lock, [] { return cap == 0; });
}
}
}
void play()
{
while (true) {
std::unique_lockstd::mutex lock(mtx);
Sleep(500);
cond_var.wait(lock, [] { return cap == cap_max; });
std::cout << “Play start” << std::endl;
do {
std::cout << "剩余播放: " << cap << std::endl;
cap -= 5;
} while (cap != 0);
std::cout << "剩余播放: " << cap << std::endl;
cond_var.notify_one();
}
}
int main() {
std::thread down1(download);
std::thread down2(download);
std::thread down3(download);
std::thread py1(play);
std::thread py2(play);
down1.join();
down2.join();
down3.join();
py1.join();
py2.join();
return 0;
}