引言

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

简单例程

std::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最简单的用法,它只是后续内容的一个引子。希望自己多学习多思考多记录多交流,做出一些微小的贡献。