【转】C++ 11 并发指南一(C++ 11 多线程初探)

时间:2023-03-09 16:01:53
【转】C++ 11 并发指南一(C++ 11 多线程初探)

引言

C++ 11自2011年发布以来已经快两年了,之前一直没怎么关注,直到最近几个月才看了一些C++ 11的新特性,算是记录一下自己学到的东西吧,和大家共勉。

相信Linux程序员都用过Pthread,但有了C++ 11的std::thread以后,你可以在语言层面编写多线程程序了,直接的好处就是多线程程序的可移植性得到了很大的提高,所以作为一名C++程序员,熟悉C++ 11的多线程编程方式还是很有益处的。

与C++ 11多线程相关的头文件

C++11新标准中引入了如下头文件来支持多线程编程,他们分别是<atomic>,<thread>,<mutex>,<condition_variable>和<future>。

  • <atomic>: 该头文件主要声明了两个类,std::atomic和std::atomic_flag,另外还声明了一套C风格的原子类型和C兼容的原子操作的函数。
  • <thread>: 改头文件主要声明了std::thread类,另外std::this_thread命名空间也在该头文件中。
  • <mutex>: 该头文件主要声明了与互斥量(mutex)相关的类,包括std::mutex系列类,std::lock_guard,std::unique_lock,以及其它的类型和函数。
  • <condition_variable>: 该头文件主要声明了与条件变量相关的类,包括std::condition_variable和std::condition_variable_any。
  • <future>: 该头文件主要声明了std::promise,std::package_task 两个Provider类,以及std::future和std::shared_future两个Future类,另外还有一些与之相关的类型和函数,std::async()函数就声明在此头文件中。

std::thread "Hello thread"

下面是一个最简单的使用std::thread类的例子:

 #include <stdio.h>
#include <stdlib.h> #include <iostream> // std::cout
#include <thread> // std::thread void thread_task() {
std::cout << "hello thread" << std::endl;
} /*
* === FUNCTION =========================================================
* Name: main
* Description: program entry routine.
* ========================================================================
*/
int main(int argc, const char *argv[])
{
std::thread t(thread_task);
t.join(); return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */

Makefile如下:

all:Thread

CC=g++
CPPFLAGS=-Wall -std=c++ -ggdb
LDFLAGS=-pthread Thread:Thread.o
$(CC) $(LDFLAGS) -o $@ $^ Thread.o:Thread.cpp
$(CC) $(CPPFLAGS) -o $@ -c $^ .PHONY:
clean clean:
rm Thread.o Thread

注意在Linux GCC4.6环境下,编译时需要加-pthread,否则执行时会出现:

$ ./Thread
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
Aborted (core dumped)

原因是GCC默认没有加载pthread库,据说在后续的版本中可以不用再编译时添加 -pthread选项。

转自:C++11 并发指南一(C++11 多线程初探)