C++学习6
基础知识
C++ examples
这里有大量的C/C++示例代码,包含各种常用的Linux接口、lib接口(如openssl)的使用等等:
https://cpp.hotexamples.com/zh/
std::thread
std::thread是C++11标准库中的一个类,用于创建并发执行的线程。它的详细用法如下:
- 头文件
#include <thread>
- 创建线程
std::thread t(func, args...);
其中,func是线程要执行的函数,args是传递给函数的参数。创建线程后,线程会立即开始执行func函数。
- 等待线程结束
t.join();
join()函数会阻塞当前线程,直到t线程执行完毕。
- 分离线程
t.detach();
detach()函数会将t线程与当前线程分离,使得t线程在后台继续执行,当前线程不再等待t线程执行完毕。
- 判断线程是否可执行
if (t.joinable()) {
// ...
}
joinable()函数用于判断线程是否可执行,如果线程已经被join()或detach(),则返回false。
- 获取线程ID
std::thread::id id = t.get_id();
get_id()函数用于获取线程的ID。
- 线程休眠
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
sleep_for()函数用于让当前线程休眠一段时间,ms是休眠的毫秒数。
- 线程同步
C++11标准库中提供了多种线程同步的机制,如互斥锁、条件变量、原子操作等。这些机制可以用于保证多个线程之间的数据同步和互斥访问。
C++ 多线程同步
https://blog.csdn.net/u011391629/article/details/103720381
https://www.cnblogs.com/haippy/p/3252041.html
上面除了常见的互斥锁,还有让A线程同步等待B线程的std::condition_variable;
#include <thread>
#include <cstdio>
#include <chrono>
#include <unistd.h>
#include <condition_variable>
std::mutex mtx;
std::condition_variable produce;
int Main()
{
// 采用共享指针从客户端线程中读取服务端返回的消息,再进行后续校验
std::shared_ptr<std::string> realReplayMsg = std::make_shared<std::string>();
// 创建子线程
std::thread t([replayMsg = realReplayMsg](){
// do something
// do replay
*replayMsg = std::string("It's replay msg.");
// 设置标志位,表示数据已经刷新完毕
std::cout << "Do notify_one" << std::endl;
// usleep(20000); // 增加20ms延时,确保服务端线程已在等待std::condition_variable变量produce
produce.notify_one();
});
t.detach();
// 等待新线程刷新完毕
std::unique_lock<std::mutex> lock(mtx);
while ((*realReplayMsg).empty()) {
produce.wait(lock); // 这个是死等
}
// while (produce.wait_for(lock, std::chrono::seconds(3)) == std::cv_status::timeout) {
// std::cout << "Wait timeout,Continue wait!" << std::endl; // 最多等待3s,如果超时则认为子线程执行失败
// return -1;
// }
std