如何在 C++ 中使用 STL 实现多线程编程?

在 c++++ 中使用 stl 实现多线程编程涉及:使用 std::thread 创建线程。使用 std::mutex 和 std::lock_guard 保护共享资源。使用 std::condition_variable 协调线程之间的条

在 c++++ 中使用 stl 实现多线程编程涉及:使用 std::thread 创建线程。使用 std::mutex 和 std::lock_guard 保护共享资源。使用 std::condition_variable 协调线程之间的条件。此方法支持并发任务,例如文件复制,其中多个线程并行处理文件块。

如何在 C++ 中使用 STL 实现多线程编程?

如何在 C++ 中使用 STL 实现多线程编程

STL(标准模板库)为 C++ 提供了一套强大的并发原语和容器,可以轻松实现多线程编程。本文将演示如何使用 STL 中的关键组件来创建多线程应用程序。

使用线程

要创建线程,请使用 std::thread 类:

std::thread t1(some_function);
t1.join(); // 等待线程完成

登录后复制

some_function 是要并发执行的函数。

互斥量和锁

互斥量可用于防止多个线程同时访问共享资源。使用 std::mutex:

std::mutex m;
{
    std::lock_guard<std::mutex> lock(m);
    // 在此处访问共享资源
} // 解除 m 的锁定

登录后复制

条件变量

条件变量允许线程等待特定条件,例如当共享资源可用时。使用 std::condition_variable:

std::condition_variable cv;
std::unique_lock<std::mutex> lock(m);
cv.wait(lock); // 等待 cv 信号
cv.notify_one(); // 唤醒一个等待线程

登录后复制

实战案例:多线程文件复制

以下代码演示如何使用 STL 实现多线程文件复制:

#include <fstream>
#include <iostream>
#include <thread>
#include <vector>

void copy_file(const std::string& src, const std::string& dst) {
    std::ifstream infile(src);
    std::ofstream outfile(dst);
    outfile << infile.rdbuf();
}

int main() {
    std::vector<std::thread> threads;
    const int num_threads = 4;

    // 创建线程池
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back(copy_file, "input.txt", "output" + std::to_string(i) + ".txt");
    }

    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }

    std::cout << "Files copied successfully!" << std::endl;
    return 0;
}

登录后复制

以上就是如何在 C++ 中使用 STL 实现多线程编程?的详细内容,更多请关注叮当号网其它相关文章!

文章来自互联网,只做分享使用。发布者:叮当,转转请注明出处:https://www.dingdanghao.com/article/521796.html

(0)
上一篇 2024-05-24 19:20
下一篇 2024-05-24 19:20

相关推荐

联系我们

在线咨询: QQ交谈

邮件:442814395@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信公众号