分类 并发编程 下的文章

C++多线程编程——C++11 thread构造函数


构造方式

std::thread默认提供了四种构造方式:

  1. default constructor:构造一个不代表任何执行线程的线程对象。
  2. initialization constructor:构造一个新的、joinable的thread对象,该方式需要一个fn函数作为参数,线程会执行这个函数。构造的完成与fn开始调用同步。
  3. copy constructor:不可用,线程对象不可被拷贝。
  4. move constructor:运用了C++11引入的新特性std::move,需要一个已有线程x通过std::move(x)作为参数。该操作不会影响被移动线程的执行,它只是传递其句柄。之后x不再表示任何执行线程。
    注意:一个线程只有在被销毁前被join或detach才是joinable的。

简单例程

cplusplus.com给出这样一个例程:

// constructing threads
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector

std::atomic<int> global_counter (0);

void increase_global (int n) { for (int i=0; i<n; ++i) ++global_counter; }

void increase_reference (std::atomic<int>& variable, int n) { for (int i=0; i<n; ++i) ++variable; }

struct C : std::atomic<int> {
  C() : std::atomic<int>(0) {}
  void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};

int main ()
{
  std::vector<std::thread> threads;

  std::cout << "increase global counter with 10 threads...\n";
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_global,1000));

  std::cout << "increase counter (foo) with 10 threads using reference...\n";
  std::atomic<int> foo(0);
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_reference,std::ref(foo),1000));

  std::cout << "increase counter (bar) with 10 threads using member...\n";
  C bar;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));

  std::cout << "synchronizing all threads...\n";
  for (auto& th : threads) th.join();

  std::cout << "global_counter: " << global_counter << '\n';
  std::cout << "foo: " << foo << '\n';
  std::cout << "bar: " << bar << '\n';

  return 0;
}

该例输出:

increase global counter using 10 threads...
increase counter (foo) with 10 threads using reference...
increase counter (bar) with 10 threads using member...
synchronizing all threads...
global_counter: 10000
foo: 10000
bar: 10000

该例展示了初始化构造函数使用的三种情形,分别为对全局变量、局部变量和成员变量进行++操作。
再来看看其他构造函数如何使用:

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

其可能输出为:

Thread 1Thread 2 executing
 executing
Thread 1 executing
Thread 2 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1Thread 2 executing
 executing
Thread 1 executing
Final value of n is 5

如之前介绍所言,t4通过std::move(t3)构造,并且不影响线程的运行,n的值仍然为5,t3也不再是线程。


C++多线程编程——C++11 thread初探


引言

由于项目需要,尝试在代码中引入多线程操作。看了一些博客介绍多线程,但普遍为入门级别的教程;尝试在项目中使用,性能又不忍直视,遂决定在博客中记录C++多线程的学习过程。
std::thread是C++11引入的新特性,在此之前只能使用Windows api或Linux的Pthread编写多线程程序,增加了代码跨平台移植的难度。C++11后,我们可以在编程语言层面使用多线程。本系列文章主要探讨C++标准库的多线程。

简单例程

std::thread类声明在头文件<thread>中。下面给出一个最基本的使用例程

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread
 
void foo() 
{
  // do stuff...
}

void bar(int x)
{
  // do stuff...
}

int main() 
{
  std::thread first (foo);     // spawn new thread that calls foo()
  std::thread second (bar,0);  // spawn new thread that calls bar(0)

  std::cout << "main, foo and bar now execute concurrently...\n";

  // synchronize threads:
  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;
}

该例输出为:

main, foo and bar now execute concurrently...
foo and bar completed.

该段代码首先声明了两个线程并在构造期间传入相应的函数和参数,之后线程就调用相应函数,该函数的参数即由线程构造函数中的参数给出。在线程执行完之前,主线程main等待子线程的执行完成(join)。

小结

本文仅仅示例了std::thread最简单的用法,它只是后续内容的一个引子。希望自己多学习多思考多记录多交流,做出一些微小的贡献。