標籤:命名空間 name c++11 linux 編程方式 strong err 好處 std
引言
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類的例子:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #include <iostream> // std::cout 5 #include <thread> // std::thread 6 7 void thread_task() { 8 std::cout << "hello thread" << std::endl; 9 }10 11 /*12 * === FUNCTION =========================================================13 * Name: main14 * Description: program entry routine.15 * ========================================================================16 */17 int main(int argc, const char *argv[])18 {19 std::thread t(thread_task);20 t.join();21 22 return EXIT_SUCCESS;23 } /* ---------- end of function main ---------- */
Makefile如下:
all:ThreadCC=g++CPPFLAGS=-Wall -std=c++11 -ggdbLDFLAGS=-pthreadThread:Thread.o $(CC) $(LDFLAGS) -o [email protected] $^Thread.o:Thread.cpp $(CC) $(CPPFLAGS) -o [email protected] -c $^.PHONY: cleanclean: rm Thread.o Thread
注意在Linux GCC4.6環境下,編譯時間需要加-pthread,否則執行時會出現:
$ ./Threadterminate called after throwing an instance of ‘std::system_error‘ what(): Operation not permittedAborted (core dumped)
原因是GCC預設沒有載入pthread庫,據說在後續的版本中可以不用再編譯時間添加 -pthread選項。
轉自:C++11 並髮指南一(C++11 多線程初探)
【轉】C++ 11 並髮指南一(C++ 11 多線程初探)