溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++11并發(fā)指南之多線程的示例分析

發(fā)布時(shí)間:2021-08-23 10:28:06 來源:億速云 閱讀:101 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)C++11并發(fā)指南之多線程的示例分析,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

與 C++11 多線程相關(guān)的頭文件

C++11 新標(biāo)準(zhǔn)中引入了四個(gè)頭文件來支持多線程編程,他們分別是<atomic> ,<thread>,<mutex>,<condition_variable>和<future>。

  • <atomic>:該頭文主要聲明了兩個(gè)類, std::atomic 和 std::atomic_flag,另外還聲明了一套 C 風(fēng)格的原子類型和與 C 兼容的原子操作的函數(shù)。

  • <thread>:該頭文件主要聲明了 std::thread 類,另外 std::this_thread 命名空間也在該頭文件中。

  • <mutex>:該頭文件主要聲明了與互斥量(mutex)相關(guān)的類,包括 std::mutex 系列類,std::lock_guard, std::unique_lock, 以及其他的類型和函數(shù)。

  • <condition_variable>:該頭文件主要聲明了與條件變量相關(guān)的類,包括 std::condition_variable 和 std::condition_variable_any。

  • <future>:該頭文件主要聲明了 std::promise, std::package_task 兩個(gè) Provider 類,以及 std::future 和 std::shared_future 兩個(gè) Future 類,另外還有一些與之相關(guān)的類型和函數(shù),std::async() 函數(shù)就聲明在此頭文件中。

std::thread "Hello world"

下面是一個(gè)最簡(jiǎn)單的使用 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 環(huán)境下,編譯時(shí)需要加 -pthread,否則執(zhí)行時(shí)會(huì)出現(xiàn):

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

原因是 GCC 默認(rèn)沒有加載 pthread 庫,據(jù)說在后續(xù)的版本中可以不用在編譯時(shí)添加 -pthread 選項(xiàng)。

關(guān)于“C++11并發(fā)指南之多線程的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI