网站首页 > 基础教程 正文
C++标准库中的多线程支持是从C++11开始引入的。下面是您提到的几个类的基本用法:
std::thread
std::thread用于创建一个新的线程。
#include <iostream>
#include <thread>
void function() {
std::cout << "Thread function\n";
}
int main() {
std::thread t(function); // 创建一个线程,执行function
t.join(); // 等待线程结束
return 0;
}
std::mutex
std::mutex用于同步线程,防止多个线程同时访问共享数据。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 创建互斥锁
void print_block(int n, char c) {
mtx.lock(); // 上锁
for (int i = 0; i < n; ++i) { std::cout << c; }
std::cout << '\n';
mtx.unlock(); // 解锁
}
int main() {
std::thread t1(print_block, 50, '*');
std::thread t2(print_block, 50, '#39;);
t1.join();
t2.join();
return 0;
}
std::lock_guard
std::lock_guard是一个互斥包装器,它提供了一个方便的RAII(资源获取即初始化)风格的机制,用于在某个作用域内持有互斥锁。
void print_block(int n, char c) {
std::lock_guard<std::mutex> lock(mtx); // 上锁,作用域结束时自动解锁
for (int i = 0; i < n; ++i) { std::cout << c; }
std::cout << '\n';
}
std::unique_lock
std::unique_lock是一个更灵活的互斥包装器,它允许延迟锁定、尝试锁定、时间锁定以及在作用域内手动解锁和重新锁定。
void print_block(int n, char c) {
std::unique_lock<std::mutex> lock(mtx, std::defer_lock); // 创建未锁定的互斥锁
// ... 在这里可以做一些不需要锁的操作 ...
lock.lock(); // 手动上锁
for (int i = 0; i < n; ++i) { std::cout << c; }
std::cout << '\n';
// lock在作用域结束时自动解锁
}
std::condition_variable
std::condition_variable用于线程间的同步。它允许一个或多个线程在某个条件成立时被唤醒。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lock(mtx);
while (!ready) { cv.wait(lock); } // 等待直到ready为true
std::cout << "thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lock(mtx);
ready = true;
cv.notify_all(); // 唤醒所有等待的线程
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(print_id, i);
std::cout << "10 threads ready to race...\n";
go(); // 准备赛跑
for (auto& th : threads) th.join();
return 0;
}
在使用多线程时,需要特别注意数据竞争和死锁等问题,确保线程安全。
猜你喜欢
- 2024-11-11 Linux下的C++ socket编程实例 linux c++ tcp
- 2024-11-11 C++11原子变量:线程安全、无锁操作的实例解析
- 2024-11-11 C++11的thread_local原理和应用范例
- 2024-11-11 知识重构-c++ : Lambda 知识重构拼音
- 2024-11-11 c++ 疑难杂症(4) std:vector c++ vector subscript out of range
- 2024-11-11 深入探索C++异步编程的奥秘 c++11异步编程
- 2024-11-11 C++ 开发中使用协程需要注意的问题
- 2024-11-11 golang极速嵌入式Linux应用开发(四)-协程与并发
- 2024-11-11 在计算机编程中,线程是指一个程序内部的执行流程
- 2024-11-11 C++ std:decay、std:bind、std:packaged_task 在模版编程的实践
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)