温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++11并发指南之多线程的示例分析

发布时间:2021-08-23 10:28:06 来源:亿速云 阅读:94 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关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 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 选项。

关于“C++11并发指南之多线程的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI