【C/C++開發】C++11 併發指南一(C++11 多線程初探)

引言

C++11 自2011年發佈以來已經快兩年了,以前一直沒怎麼關注,直到最近幾個月纔看了一些 C++11 的新特性,從此幾篇博客我都會寫一些關於 C++11 的特性,算是記錄一下本身學到的東西吧,和你們共勉。php

相信 Linux 程序員都用過 Pthread, 但有了 C++11 的 std::thread 之後,你能夠在語言層面編寫多線程程序了,直接的好處就是多線程程序的可移植性獲得了很大的提升,因此做爲一名 C++ 程序員,熟悉 C++11 的多線程編程方式仍是頗有益處的。css

若是你對 C++11 不太熟悉,建議先看看維基百科上關於 C++11 新特性的介紹,中文C++11介紹英文C++11介紹 ,另外C++之父 Bjarne Stroustrup 的關於 C++11 的 FAQ 也是必看的,我也收集了一些關於C++11的資料,供你們查閱:html

資料匯

http://www.open-std.org/jtc1/sc22/wg21/ios

C++0x/C++11 Support in GCC:http://gcc.gnu.org/projects/cxx0x.htmlc++

What is C++0x:https://www2.research.att.com/~bs/what-is-2009.pdf程序員

Overview of the New C++http://www.artima.com/shop/overview_of_the_new_cpp編程

Overview of the New C++ (C++0x).pdf:http://ishare.iask.sina.com.cn/f/20120005.html?from=likepromise

A Brief Look at C++0xhttp://www.artima.com/cppsource/cpp0x.html多線程

Summary of C++11 Feature Availability in gcc and MSVC:http://www.aristeia.com/C++11/C++11FeatureAvailability.htmasync

C++ 11: Come Closer:http://www.codeproject.com/Articles/344282/Cplusplus-11-Come-Closer

C++11 threads, locks and condition variables: http://www.codeproject.com/Articles/598695/Cplusplus11-threads-locks-and-condition-variables

Move Semantics and Perfect Forwarding in C++11:http://www.codeproject.com/Articles/397492/Move-Semantics-and-Perfect-Forwarding-in-Cplusplus

http://solarianprogrammer.com/categories/C++11/

C++11 Concurrency:http://www.baptiste-wicht.com/2012/03/cpp11-concurrency-part1-start-threads/

http://www.hpl.hp.com/personal/Hans_Boehm/misc_slides/sfacm-cleaned.pdf

http://en.cppreference.com/w/cpp/thread

http://isocpp.org/blog/2012/12/c11-a-cheat-sheet-alex-sinyakov

The Biggest Changes in C++11:http://blog.smartbear.com/c-plus-plus/the-biggest-changes-in-c11-and-why-you-should-care/

Ten C++11 Features Every C++ Developer Should Use:http://www.codeproject.com/Articles/570638/Ten-Cplusplus11-Features-Every-Cplusplus-Developer

 C++11 – A Glance [part 1 of n]:http://www.codeproject.com/Articles/312029/Cplusplus11-A-Glance-part-1-of-n

 C++11 – A Glance [part 2 of n]:http://www.codeproject.com/Articles/314415/Cplusplus11-A-Glance-part-2-of-n

C++11(及現代C++風格)和快速迭代式開發:http://mindhacks.cn/2012/08/27/modern-cpp-practices/

Lambda Functions in C++11 - the Definitive Guide:http://www.cprogramming.com/c++11/c++11-lambda-closures.html

Better types in C++11 - nullptr, enum classes (strongly typed enumerations) and cstdint:http://www.cprogramming.com/c++11/c++11-nullptr-strongly-typed-enum-class.html

Rvalue-references-and-move-semantics-in-c++11:http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html

http://www.gotw.ca/publications/index.htm

http://www.devx.com/SpecialReports/Door/38865

Multi-threading in C++0x:http://accu.org/index.php/journals/1584

C++ 0X feature summary cheat sheat:http://www.iesensor.com/blog/2011/05/31/c-0x-feature-summary-cheat-sheat/

Multithreading in C++0x part 1: Starting Threads:http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-1-starting-threads.html

http://en.cppreference.com/w/cpp/thread

http://www.cplusplus.com/reference/multithreading/

好了,下面來講正題吧 ;-)

與 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 world"

下面是一個最簡單的使用 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++11 -ggdb
LDFLAGS=-pthread

Thread:Thread.o
    $(CC) $(LDFLAGS) -o $@ $^

Thread.o:Thread.cc
    $(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 選項。

相關文章
相關標籤/搜索