C++11并发编程:深入解析std::thread的使用方法?

2026-04-29 17:016阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1211个文字,预计阅读时间需要5分钟。

C++11并发编程:深入解析std::thread的使用方法?

上一篇博客《C++11+并发指南一(C++11+多线程初探)》中,仅提到了std::thread的基本用法,并给出一个最简单的例子。本文将详细介绍std::thread的用法。

std::thread在thread头文件中定义,用于创建和管理线程。其基本用法如下:

1. 创建线程:使用std::thread构造函数创建线程,并传入要执行的函数和参数。

2.等待线程结束:使用join()、detach()或wait_for_all()等方法等待线程结束。

3.线程同步:使用互斥锁(mutex)、条件变量(condition variable)等同步机制保证线程间的数据安全。

以下是一个简单的例子:

cpp

#include #include

void printNumber(int n) { for (int i=0; i

int main() { std::thread t1(printNumber, 10); std::thread t2(printNumber, 20);

t1.join(); // 等待t1线程结束 t2.join(); // 等待t2线程结束

return 0;}

在上面的例子中,我们创建了两个线程t1和t2,分别执行printNumber函数,并传入不同的参数。使用join()方法等待每个线程执行完毕后再继续执行main函数。

C++11并发编程:深入解析std::thread的使用方法?

上一篇博客《C++11 并发指南一(C++11 多线程初探)》中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用法。

std::thread 在 <thread> 头文件中声明,因此使用 std::thread 时需要包含 <thread> 头文件。

std::thread 构造

default (1)

thread() noexcept; initialization (2)

template <class Fn, class... Args> explicit thread (Fn&& fn, Args&&... args); copy [deleted] (3)

thread (const thread&) = delete; move (4)

thread (thread&& x) noexcept;

(1). 默认构造函数,创建一个空的 thread 执行对象。
(2). 初始化构造函数,创建一个 thread对象,该 thread对象可被 joinable,新产生的线程会调用 fn 函数,该函数的参数由 args 给出。
(3). 拷贝构造函数(被禁用),意味着 thread 不可被拷贝构造。
(4). move 构造函数,move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。

注意:可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached.

std::thread 各种构造函数例子如下(参考):

#include <iostream> #include <utility> #include <thread> #include <chrono> #include <functional> #include <atomic> void f1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread " << n << " executing\n"; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void f2(int& n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 2 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int main() { int n = 0; std::thread t1; // t1 is not a thread std::thread t2(f1, n + 1); // pass by value std::thread t3(f2, std::ref(n)); // pass by reference std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread t2.join(); t4.join(); std::cout << "Final value of n is " << n << '\n'; }

move 赋值操作

move (1)

thread& operator= (thread&& rhs) noexcept; copy [deleted] (2)

thread& operator= (const thread&) = delete;

(1). move 赋值操作,如果当前对象不可 joinable,需要传递一个右值引用(rhs)给 move 赋值操作;如果当前对象可被 joinable,则 terminate() 报错。
(2). 拷贝赋值操作被禁用,thread 对象不可被拷贝。

请看下面的例子:

#include <stdio.h> #include <stdlib.h> #include <chrono> // std::chrono::seconds #include <iostream> // std::cout #include <thread> // std::thread, std::this_thread::sleep_for void thread_task(int n) { std::this_thread::sleep_for(std::chrono::seconds(n)); std::cout << "hello thread " << std::this_thread::get_id() << " paused " << n << " seconds" << std::endl; } /* * === FUNCTION ========================================================= * Name: main * Description: program entry routine. * ======================================================================== */ int main(int argc, const char *argv[]) { std::thread threads[5]; std::cout << "Spawning 5 threads...\n"; for (int i = 0; i < 5; i++) { threads[i] = std::thread(thread_task, i + 1); } std::cout << "Done spawning threads! Now wait for them to join\n"; for (auto& t: threads) { t.join(); } std::cout << "All threads joined.\n"; return EXIT_SUCCESS; } /* ---------- end of function main ---------- */

其他成员函数

get_id
获取线程 ID。

joinable
检查线程是否可被 join。

join
Join 线程。

detach
Detach 线程

swap
Swap 线程 。

native_handle
返回 native handle。

hardware_concurrency [static]
检测硬件并发特性。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

本文共计1211个文字,预计阅读时间需要5分钟。

C++11并发编程:深入解析std::thread的使用方法?

上一篇博客《C++11+并发指南一(C++11+多线程初探)》中,仅提到了std::thread的基本用法,并给出一个最简单的例子。本文将详细介绍std::thread的用法。

std::thread在thread头文件中定义,用于创建和管理线程。其基本用法如下:

1. 创建线程:使用std::thread构造函数创建线程,并传入要执行的函数和参数。

2.等待线程结束:使用join()、detach()或wait_for_all()等方法等待线程结束。

3.线程同步:使用互斥锁(mutex)、条件变量(condition variable)等同步机制保证线程间的数据安全。

以下是一个简单的例子:

cpp

#include #include

void printNumber(int n) { for (int i=0; i

int main() { std::thread t1(printNumber, 10); std::thread t2(printNumber, 20);

t1.join(); // 等待t1线程结束 t2.join(); // 等待t2线程结束

return 0;}

在上面的例子中,我们创建了两个线程t1和t2,分别执行printNumber函数,并传入不同的参数。使用join()方法等待每个线程执行完毕后再继续执行main函数。

C++11并发编程:深入解析std::thread的使用方法?

上一篇博客《C++11 并发指南一(C++11 多线程初探)》中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用法。

std::thread 在 <thread> 头文件中声明,因此使用 std::thread 时需要包含 <thread> 头文件。

std::thread 构造

default (1)

thread() noexcept; initialization (2)

template <class Fn, class... Args> explicit thread (Fn&& fn, Args&&... args); copy [deleted] (3)

thread (const thread&) = delete; move (4)

thread (thread&& x) noexcept;

(1). 默认构造函数,创建一个空的 thread 执行对象。
(2). 初始化构造函数,创建一个 thread对象,该 thread对象可被 joinable,新产生的线程会调用 fn 函数,该函数的参数由 args 给出。
(3). 拷贝构造函数(被禁用),意味着 thread 不可被拷贝构造。
(4). move 构造函数,move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。

注意:可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached.

std::thread 各种构造函数例子如下(参考):

#include <iostream> #include <utility> #include <thread> #include <chrono> #include <functional> #include <atomic> void f1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread " << n << " executing\n"; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void f2(int& n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 2 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int main() { int n = 0; std::thread t1; // t1 is not a thread std::thread t2(f1, n + 1); // pass by value std::thread t3(f2, std::ref(n)); // pass by reference std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread t2.join(); t4.join(); std::cout << "Final value of n is " << n << '\n'; }

move 赋值操作

move (1)

thread& operator= (thread&& rhs) noexcept; copy [deleted] (2)

thread& operator= (const thread&) = delete;

(1). move 赋值操作,如果当前对象不可 joinable,需要传递一个右值引用(rhs)给 move 赋值操作;如果当前对象可被 joinable,则 terminate() 报错。
(2). 拷贝赋值操作被禁用,thread 对象不可被拷贝。

请看下面的例子:

#include <stdio.h> #include <stdlib.h> #include <chrono> // std::chrono::seconds #include <iostream> // std::cout #include <thread> // std::thread, std::this_thread::sleep_for void thread_task(int n) { std::this_thread::sleep_for(std::chrono::seconds(n)); std::cout << "hello thread " << std::this_thread::get_id() << " paused " << n << " seconds" << std::endl; } /* * === FUNCTION ========================================================= * Name: main * Description: program entry routine. * ======================================================================== */ int main(int argc, const char *argv[]) { std::thread threads[5]; std::cout << "Spawning 5 threads...\n"; for (int i = 0; i < 5; i++) { threads[i] = std::thread(thread_task, i + 1); } std::cout << "Done spawning threads! Now wait for them to join\n"; for (auto& t: threads) { t.join(); } std::cout << "All threads joined.\n"; return EXIT_SUCCESS; } /* ---------- end of function main ---------- */

其他成员函数

get_id
获取线程 ID。

joinable
检查线程是否可被 join。

join
Join 线程。

detach
Detach 线程

swap
Swap 线程 。

native_handle
返回 native handle。

hardware_concurrency [static]
检测硬件并发特性。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。