std::thread

definition

thread() noexcept;    (1)   (since C++11)
thread( thread&& other ) noexcept;    (2)   (since C++11)
template< class Function, class... Args > 
explicit thread( Function&& f, Args&&... args );    (3) (since C++11)
thread(const thread&) = delete;    (4)  (since C++11)

practice

### 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]。 ####
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值