草庐IT

C++ std::thread

runoob 2023-03-28 原文

c++ 11 之后有了标准的线程库:std::thread。

之前一些编译器使用 C++11 的编译参数是 -std=c++11

g++ -std=c++11 test.cpp 

std::thread 构造函数

默认构造函数 thread() noexcept;
初始化构造函数 template <class Fn, class... Args>
explicit thread(Fn&& fn, Args&&... args);
拷贝构造函数 [deleted] thread(const thread&) = delete;
Move 构造函数 thread(thread&& x) noexcept;
  • 默认构造函数,创建一个空的 std::thread 执行对象。
  • 初始化构造函数,创建一个 std::thread 对象,该 std::thread 对象可被 joinable,新产生的线程会调用 fn 函数,该函数的参数由 args 给出。
  • 拷贝构造函数(被禁用),意味着 std::thread 对象不可拷贝构造。
  • Move 构造函数,move 构造函数(move 语义是 C++11 新出现的概念,详见附录),调用成功之后 x 不代表任何 std::thread 执行对象。

注意:可被 joinablestd::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';
}

std::thread 赋值操作

Move 赋值操作 thread& operator=(thread&& rhs) noexcept;
拷贝赋值操作 [deleted] thread& operator=(const thread&) = delete;
  • Move 赋值操作(1),如果当前对象不可 joinable,需要传递一个右值引用(rhs)给 move 赋值操作;如果当前对象可被 joinable,则会调用 terminate() 报错。
  • 拷贝赋值操作(2),被禁用,因此 std::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;
}

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;
}

其他成员函数

get_id: 获取线程 ID,返回一个类型为 std::thread::id 的对象。请看下面例子:

#include <iostream>
#include <thread>
#include <chrono>

void foo()
{
  std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
  std::thread t1(foo);
  std::thread::id t1_id = t1.get_id();

  std::thread t2(foo);
  std::thread::id t2_id = t2.get_id();

  std::cout << "t1's id: " << t1_id << '\n';
  std::cout << "t2's id: " << t2_id << '\n';

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

joinable: 检查线程是否可被 join。检查当前的线程对象是否表示了一个活动的执行线程,由默认构造函数创建的线程是不能被 join 的。另外,如果某个线程 已经执行完任务,但是没有被 join 的话,该线程依然会被认为是一个活动的执行线程,因此也是可以被 join 的。

#include <iostream>
#include <thread>
#include <chrono>

void foo()
{
  std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
  std::thread t;
  std::cout << "before starting, joinable: " << t.joinable() << '\n';

  t = std::thread(foo);
  std::cout << "after starting, joinable: " << t.joinable() << '\n';

  t.join();
}
join: Join 线程,调用该函数会阻塞当前线程,直到由 *this 所标示的线程执行完毕 join 才返回。

#include <iostream>
#include <thread>
#include <chrono>

void foo()
{
  // simulate expensive operation
  std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar()
{
  // simulate expensive operation
  std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
  std::cout << "starting first helper...\n";
  std::thread helper1(foo);

  std::cout << "starting second helper...\n";
  std::thread helper2(bar);

  std::cout << "waiting for helpers to finish..." << std::endl;
  helper1.join();
  helper2.join();

  std::cout << "done!\n";
}

detach: Detach 线程。 将当前线程对象所代表的执行实例与该线程对象分离,使得线程的执行可以单独进行。一旦线程执行完毕,它所分配的资源将会被释放。

调用 detach 函数之后:

  • *this 不再代表任何的线程执行实例。
  • joinable() == false
  • get_id() == std::thread::id()

另外,如果出错或者 joinable() == false,则会抛出 std::system_error。

#include <iostream>
#include <chrono>
#include <thread>
 
void independentThread() 
{
    std::cout << "Starting concurrent thread.\n";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Exiting concurrent thread.\n";
}
 
void threadCaller() 
{
    std::cout << "Starting thread caller.\n";
    std::thread t(independentThread);
    t.detach();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Exiting thread caller.\n";
}
 
int main() 
{
    threadCaller();
    std::this_thread::sleep_for(std::chrono::seconds(5));
}

swap: Swap 线程,交换两个线程对象所代表的底层句柄(underlying handles)。

#include <iostream>
#include <thread>
#include <chrono>

void foo()
{
  std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar()
{
  std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
  std::thread t1(foo);
  std::thread t2(bar);

  std::cout << "thread 1 id: " << t1.get_id() << std::endl;
  std::cout << "thread 2 id: " << t2.get_id() << std::endl;

  std::swap(t1, t2);

  std::cout << "after std::swap(t1, t2):" << std::endl;
  std::cout << "thread 1 id: " << t1.get_id() << std::endl;
  std::cout << "thread 2 id: " << t2.get_id() << std::endl;

  t1.swap(t2);

  std::cout << "after t1.swap(t2):" << std::endl;
  std::cout << "thread 1 id: " << t1.get_id() << std::endl;
  std::cout << "thread 2 id: " << t2.get_id() << std::endl;

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

执行结果如下:

thread 1 id: 1892
thread 2 id: 2584
after std::swap(t1, t2):
thread 1 id: 2584
thread 2 id: 1892
after t1.swap(t2):
thread 1 id: 1892
thread 2 id: 2584

native_handle: 返回 native handle(由于 std::thread 的实现和操作系统相关,因此该函数返回与 std::thread 具体实现相关的线程句柄,例如在符合 Posix 标准的平台下(如 Unix/Linux)是 Pthread 库)。

#include <thread>
#include <iostream>
#include <chrono>
#include <cstring>
#include <pthread.h>

std::mutex iomutex;
void f(int num)
{
  std::this_thread::sleep_for(std::chrono::seconds(1));

 sched_param sch;
 int policy; 
 pthread_getschedparam(pthread_self(), &policy, &sch);
 std::lock_guard<std::mutex> lk(iomutex);
 std::cout << "Thread " << num << " is executing at priority "
           << sch.sched_priority << '\n';
}

int main()
{
  std::thread t1(f, 1), t2(f, 2);

  sched_param sch;
  int policy; 
  pthread_getschedparam(t1.native_handle(), &policy, &sch);
  sch.sched_priority = 20;
  if(pthread_setschedparam(t1.native_handle(), SCHED_FIFO, &sch)) {
      std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n';
  }

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

执行结果如下:

Thread 2 is executing at priority 0 Thread 1 is executing at priority 20

hardware_concurrency [static]: 检测硬件并发特性,返回当前平台的线程实现所支持的线程并发数目,但返回值仅仅只作为系统提示(hint)。

#include <iostream>
#include <thread>

int main() {
  unsigned int n = std::thread::hardware_concurrency();
  std::cout << n << " concurrent threads are supported.\n";
}

std::this_thread 命名空间中相关辅助函数介绍

get_id: 获取线程 ID。

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

std::mutex g_display_mutex;

void foo()
{
  std::thread::id this_id = std::this_thread::get_id();

  g_display_mutex.lock();
  std::cout << "thread " << this_id << " sleeping...\n";
  g_display_mutex.unlock();

  std::this_thread::sleep_for(std::chrono::seconds(1));
}

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

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

yield: 当前线程放弃执行,操作系统调度另一线程继续执行。

#include <iostream>
#include <chrono>
#include <thread>

// "busy sleep" while suggesting that other threads run 
// for a small amount of time
void little_sleep(std::chrono::microseconds us)
{
  auto start = std::chrono::high_resolution_clock::now();
  auto end = start + us;
  do {
      std::this_thread::yield();
  } while (std::chrono::high_resolution_clock::now() < end);
}

int main()
{
  auto start = std::chrono::high_resolution_clock::now();

  little_sleep(std::chrono::microseconds(100));

  auto elapsed = std::chrono::high_resolution_clock::now() - start;
  std::cout << "waited for "
            << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count()
            << " microseconds\n";
}

sleep_until: 线程休眠至某个指定的时刻(time point),该线程才被重新唤醒。

template< class Clock, class Duration >
void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time );

sleep_for: 线程休眠某个指定的时间片(time span),该线程才被重新唤醒,不过由于线程调度等原因,实际休眠时间可能比 sleep_duration 所表示的时间片更长。

#include <iostream>
#include <chrono>
#include <thread>

int main()
{
  std::cout << "Hello waiter" << std::endl;
  std::chrono::milliseconds dura( 2000 );
  std::this_thread::sleep_for( dura );
  std::cout << "Waited 2000 ms\n";
}

执行结果如下:

Hello waiter
Waited 2000 ms

来源:https://github.com/forhappy/Cplusplus-Concurrency-In-Practice/blob/master/zh/chapter3-Thread/Introduction-to-Thread.md

有关C++ std::thread的更多相关文章

  1. ruby - 不调用 Thread#join 可以吗? - 2

    可以不调用Thread#join吗?在这种情况下,我不关心线程是否爆炸-我只希望Unicorn继续处理。classMyMiddlewaredefinitialize(app)@app=appenddefcall(env)t=Thread.new{sleep1}t.join#isitokifIskipthis?@app.callenvendend我会得到“僵尸线程”或类似的东西吗? 最佳答案 不调用join完全没问题-事实上,多线程代码通常根本不需要join。如果您需要阻塞直到新线程完成,您应该只调用join。您不会得到“僵尸”线程。

  2. ruby - 如何修改矩阵(Ruby std-lib Matrix 类)? - 2

    我理解RubystdlibMatrix是不可修改的,也就是说,例如。m=Matrix.zero(3,4)不会写m[0,1]=7但我非常想做...我可以用笨拙的编程来做,比如defmodify_value_in_a_matrix(matrix,row,col,newval)ary=(0...m.row_size).map{|i|m.rowi}.map(&:to_a)ary[row][col]=newvalMatrix[*ary]end...或者作弊,比如Matrix.send:[]=,0,1,7但我想知道,这一定是人们一直遇到的问题。有没有一些标准的、习惯的方法可以做到这一点,而不必使用

  3. ruby - Ruby Thread 的派生类? - 2

    我在C++世界生活了很多年,而我才刚刚开始使用Ruby。我有一个类,我想做一个线程。在Ruby中,从Thread派生类是错误的吗?我看到的例子使用了下面的概念。Thread.new{}这样做会错吗?classMyThreadend 最佳答案 我认为这确实是一个关于领域建模的问题。如果您想扩展/增强线程的行为方式——例如添加调试或性能输出,那么您正在做的事情没有任何问题,但我认为这不是您想要的。您可能想在您的领域中使用事件对象对某些概念进行建模。在那种情况下,标准Ruby方法更好,因为它允许您在不改变领域模型的情况下实现这一目标。继承

  4. ruby-on-rails - 可以在 Thread::handle_interrupt block 之外异步处理 ruby​​ 异常吗? - 2

    乍一看,我以为新的ruby​​2.0Thread.handle_interrupt会解决我所有的异步中断问题,但除非我弄错了,否则我无法让它做我想做的事(我的问题在最后和标题中)。从文档中,我可以看到如何避免在某个block中接收中断,将它们推迟到另一个block。这是一个示例程序:duration=ARGV.shift.to_it=Thread.newdoThread.handle_interrupt(RuntimeError=>:never)do5.times{putc'-';sleep1}Thread.handle_interrupt(RuntimeError=>:immedia

  5. ruby - Thread#run 和 Thread#wakeup 之间的区别? - 2

    在Ruby中,Thread#run和Thread#wakup有什么区别?RDoc指定scheduler不使用Thread#wakeup调用,但这是什么意思?何时使用唤醒与运行的示例?谢谢。编辑:我看到Thread#wakup导致线程变为可运行状态,但如果在执行Thread#run之前它不会执行(无论如何都会唤醒线程),它有什么用?有人可以提供一个示例,其中wakeup做了一些有意义的事情吗?出于好奇=) 最佳答案 这里有一个例子来说明它的含义(来自here的代码示例):线程唤醒thread=Thread.newdoThread.st

  6. Ruby 并发 : non-blocking I/O vs threads - 2

    我正在研究Ruby(1.9.3-p0)中的并发性,并创建了一个非常简单的I/O密集型代理任务。首先,我尝试了非阻塞方法:require'rack'require'rack/fiber_pool'require'em-http'require'em-synchrony'require'em-synchrony/em-http'proxy=lambda{|*|result=EM::Synchrony.syncEventMachine::HttpRequest.new('http://google.com').get[200,{},[result.response]]}useRack::Fi

  7. ruby - 什么时候需要将参数传递给 `Thread.new` ? - 2

    在线程外部定义的局部变量似乎从内部可见,因此Thread.new的以下两种用法似乎是相同的:a=:fooThread.new{putsa}#=>:fooThread.new(a){|a|putsa}#=>:foodocument举个例子:arr=[]a,b,c=1,2,3Thread.new(a,b,c){|d,e,f|arr[1,2,3]但由于a、b、c在创建的线程内部是可见的,所以这也应该与:arr=[]a,b,c=1,2,3Thread.new{d,e,f=a,b,c;arr[1,2,3]有区别吗?什么时候需要将局部变量作为参数传递给Thread.new?

  8. ruby - Thread.join 阻塞主线程 - 2

    调用Thread.join会阻塞当前(主)线程。然而,当主线程退出时,不调用join会导致所有生成的线程被杀死。如何在不阻塞主线程的情况下在Ruby中生成持久性子线程?这是连接的典型用法。foriin1..100doputs"Creatingthread#{i}"t=Thread.new(i)do|j|sleep1puts"Thread#{j}done"endt.joinendputs"#{Thread.list.size}threads"这给出了Creatingthread1Thread1doneCreatingthread2Thread2done...1threads但是我正在寻找

  9. system.threading.Timer每天尝试同时制作计时器 - 2

    我在控制台服务应用中使用system.threading.timer,并尝试每天同时制作计时器。最初,如果我在时间之前启动该应用程序,我会很好。就像我的时间是10:05,我从10:00启动该应用程序,我们很好。但是,如果我从10:06开始,我就不知道如何告诉时间台下24小时。谢谢你的帮助!publicvoidSetUpTimer(TimeSpanalertTime){DateTimecurrent=DateTime.Now;TimeSpantimeToGo=alertTime-current.TimeOfDay;if(timeToGo{EventLog.WriteEntry("MhyApp",

  10. 我们可以为两个不同的IBM BPM STD 8.5.7环境设置单个数据库吗? - 2

    我们想为IBMBPMSTD8.5.7设置DRServer,并计划使用ProdDB(Oracle),以便如果出于某种原因,PRODBPM环境变得不可用,我们可以在IBMBPM博士中使用ProdDB数据。这可能吗?需要考虑哪些因素?目前,我们使用ProdDB的快照,并使用此DB快照作为COB,所有服务器都启动了,但是当我们打开ProcessAdminConsole时,我们看不到“已安装的应用程序”选项和左侧菜单来管理用户。BPMAdminID博士似乎没有必要的角色来获取详细信息。看答案首先,我想向您指出下面的文章;IBM业务流程经理的灾难恢复指南请注意配置数据和运行按照本文定义的数据。由于某些配置

随机推荐