c 多執行緒 二

2021-07-06 07:15:34 字數 1369 閱讀 3441

c++11 是 2011 年 9 月 1 號發布的。c++11 在 c++03 的基礎上做了大量的改進,引入了很多新的特性,比如 lambda 表示式,右值引用,統一的列表初始化方式,正規表示式等等。當然,其中最令人激動的特性是新標準引入了原子操作類和執行緒支援庫。c++ 一直在語言層面缺少對多執行緒的支援,因此 c++11 新標準基本上彌補了這一缺陷。可以毫不誇張地說,c++11 相當於一門新的程式語言。

相信 linux 程式設計師都用過 pthread, 但有了 c++11 的 std::thread 以後,你可以在語言層面編寫多執行緒程式了,直接的好處就是多執行緒程式的可移植性得到了很大的提高,所以作為一名 c++ 程式設計師,熟悉 c++11 的多執行緒程式設計方式還是很有益處的。

與 c++11 多執行緒相關的標頭檔案

c++11 新標準中引入了五個標頭檔案來支援多執行緒程式設計,它們分別是, , ,

std::thread"hello world"

下面是乙個最簡單的使用 std::thread 類的例子

#include #include #include // std::cout

#include // std::thread

void thread_task()

int main(int argc, const char *argv)

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 選項。 如果 -std=c++11 不被支援,請嘗試使用 -std=c++0x 代替並確保gcc已經公升級。

C 多執行緒(二)

每次建立乙個執行緒,都會花費幾百微秒級別的時間來建立乙個私有的區域性棧,每個執行緒預設使用1m的記憶體。這個可以在使用thread類的建構函式時設定 new thread new threadstart go 2 new thread new parameterizedthreadstart go ...

C 多執行緒(二)

c c runtime 多執行緒函式 一 簡單例項 主線程建立2個執行緒t1和t2,建立時2個執行緒就被掛起,後來呼叫resumethread恢復2個執行緒,使其開始執行,呼叫waitforsingleobject等待2個執行緒執行完,然後推出主線程即結束程序。二解釋1 如果你正在編寫c c 決不應...

C 多執行緒系列(二)

static void main string args thread.start console.readkey static void threadone string content static void main string args static void threadone obje...