std::thread简单使用

本文介绍了C++标准库中用于多线程编程的类,涵盖创建线程、传递参数给线程函数、设置后台线程以及线程同步等内容。通过示例展示基本用法,强调多线程编程在实际应用中更复杂,需深入学习并遵循最佳实践。

std::thread 是 C++ 标准库中用于多线程编程的类。它允许你创建和管理线程,使程序能够并发执行不同的任务。以下是关于 std::thread 的详细介绍以及几个示例说明:

创建线程

你可以使用 std::thread 构造函数创建新的线程,并将要执行的函数传递给它。以下是创建线程的基本示例:

#include <iostream>
#include <thread>

void threadFunction() {
    // 这个函数将在新线程中执行
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    // 创建新线程并启动
    std::thread t(threadFunction);

    // 主线程继续执行自己的任务

    // 等待新线程结束
    t.join();

    return 0;
}

在上述示例中,我们创建了一个名为 t 的新线程,并将 threadFunction 函数传递给它。主线程继续执行自己的任务,然后使用 t.join() 等待新线程的结束。

传递参数给线程函数

你可以通过将参数传递给线程函数来向线程传递数据。以下是一个带有参数的示例:

#include <iostream>
#include <thread>

void threadFunction(int x, const std::string& str) {
    std::cout << "Received: " << x << " and " << str << std::endl;
}

int main() {
    int data = 42;
    std::string message = "Hello from main thread";

    // 创建新线程并传递参数
    std::thread t(threadFunction, data, message);

    // 等待新线程结束
    t.join();

    return 0;
}

后台线程

有时,你可能希望创建一个后台线程,它会在程序退出时自动终止,而不需要显式调用 join()。你可以使用 std::thread::detach() 将线程设置为后台线程:

#include <iostream>
#include <thread>

void threadFunction() {
    // 后台线程执行的任务
    std::cout << "Background thread is running." << std::endl;
}

int main() {
    // 创建后台线程
    std::thread t(threadFunction);

    // 分离线程,使其成为后台线程
    t.detach();

    // 主线程继续执行自己的任务

    // 注意:不要在后台线程结束前退出程序,否则可能导致线程终止的不确定行为

    return 0;
}

线程同步

在多线程编程中,需要谨慎处理共享资源,以避免竞态条件和数据访问冲突。C++ 提供了一些线程同步工具,如 std::mutex 和 std::lock_guard,来帮助你确保线程安全。以下是一个使用 std::mutex 的示例,保护共享数据的访问:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;  // 用于保护共享资源的互斥锁
int sharedData = 0;

void threadFunction() {
    // 加锁互斥锁,以确保线程安全访问共享数据
    std::lock_guard<std::mutex> lock(mtx);
    sharedData++;
}

int main() {
    std::thread t1(threadFunction);
    std::thread t2(threadFunction);

    t1.join();
    t2.join();

    // 输出共享数据的值
    std::cout << "Shared data: " << sharedData << std::endl;

    return 0;
}

在这个示例中,我们使用 std::mutex 来保护 sharedData 的访问,以确保两个线程不会同时修改它。

这些示例只是 std::thread 的一些基本用法。在实际应用中,多线程编程可能更复杂,需要更多的同步和线程管理。因此,确保深入学习 C++ 多线程编程并遵循最佳实践,以避免潜在的问题。

### C++ 中 `std::thread` 的使用方法及多线程编程示例 #### 1. 基本概念 `std::thread` 是 C++ 标准库中用于创建和管理线程的,提供了简单直接的方式来启动新线程以执行用户定义的函数[^3]。通过构造 `std::thread` 对象,并将目标函数作为参数传递给构造函数,可以轻松实现多线程编程。 #### 2. 构造函数与主要成员函数 `std::thread` 提供了多种构造函数来支持不同型的函数调用,包括普通函数、lambda 表达式、函数对象等。此外,它还提供了以下主要成员函数: - `join()`: 等待线程完成。 - `detach()`: 将线程与当前线程分离,使其独立运行[^4]。 - `get_id()`: 获取线程的唯一标识符[^5]。 - `joinable()`: 检查线程是否可被 `join` 或 `detach`。 #### 3. 示例代码 以下是一个简单的多线程编程示例,展示了如何使用 `std::thread` 创建和管理线程。 ```cpp #include <iostream> #include <thread> #include <vector> void thread_function(int id) { std::cout << "Thread ID: " << id << ", Thread native ID: " << std::this_thread::get_id() << std::endl; } int main() { const int num_threads = 5; std::vector<std::thread> threads; // 创建多个线程 for (int i = 0; i < num_threads; ++i) { threads.emplace_back(thread_function, i); } // 等待所有线程完成 for (auto& t : threads) { if (t.joinable()) { t.join(); } } return 0; } ``` 在上述代码中,通过 `std::thread` 创建了多个线程,并使用 `join()` 方法等待它们完成。每个线程执行 `thread_function` 函数,并输出其 ID 和原生线程 ID[^5]。 #### 4. 使用 `detach()` 分离线程 以下代码展示了如何使用 `detach()` 方法使线程独立运行: ```cpp #include <iostream> #include <thread> #include <chrono> void detached_thread_function() { std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "Detached thread is running!" << std::endl; } int main() { std::thread t(detached_thread_function); t.detach(); // 分离线程 std::this_thread::sleep_for(std::chrono::seconds(3)); // 等待一段时间 std::cout << "Main thread is finishing." << std::endl; return 0; } ``` 在这个例子中,`detach()` 方法使得线程独立于主线程运行,即使主线程结束,分离的线程仍然会继续执行[^4]。 #### 5. 线程池示例 以下是一个简单的线程池实现,展示了如何利用 `std::thread` 管理多个任务: ```cpp #include <iostream> #include <vector> #include <queue> #include <thread> #include <functional> #include <mutex> #include <condition_variable> class ThreadPool { public: ThreadPool(size_t threads) : stop(false) { for (size_t i = 0; i < threads; ++i) { workers.emplace_back([this] { while (true) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) { return; } task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } }); } } template<class F> void enqueue(F&& f) { { std::unique_lock<std::mutex> lock(queue_mutex); tasks.emplace(std::forward<F>(f)); } condition.notify_one(); } ~ThreadPool() { { std::unique_lock<std::mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for (std::thread& worker : workers) { worker.join(); } } private: std::vector<std::thread> workers; std::queue<std::function<void()>> tasks; std::mutex queue_mutex; std::condition_variable condition; bool stop; }; void task_function(int id) { std::cout << "Task " << id << " is running on thread " << std::this_thread::get_id() << std::endl; } int main() { ThreadPool pool(4); for (int i = 0; i < 10; ++i) { pool.enqueue([i]() { task_function(i); }); } return 0; } ``` 在这个线程池实现中,`std::thread` 被用来管理多个工作线程,每个线程从任务队列中获取任务并执行[^1]。 ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

telllong

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值