C++/C编程指南:C++11 并发多线程01

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() 函数就声明在此头文件中。

demo

std::thread

C++的线程对象,和Java的线程非常不同,C++中线程较轻量级,线程的创建和执行的消耗较小,但是同时C++中线程没有明确的状态信息。
1. thread创建后,C++始终尝试在一个新线程中执行人物,如果失败返回std::system_error
2. 没有线程运行结果的接口,无法获得执行结果。
3. 如果有异常在thread中发生,并且没有被捕获,std::terminate将会被调用
4. 只能调用join去结束线程,或者detach去转成后台线程执行。否则当thread被析构时,程序会被abort。
5. 如果线程detach并且main函数执行结束,所以的detach线程会被终止.
6. 线程只可以通过std::move转移,不可以复制。
创建线程的方式

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream> // std::cout
#include <thread>   // std::thread
void thread_task() {
	std::cout << "hello thread" << std::endl;
}
int main(int argc, const char *argv[])
{
	std::thread t(thread_task);
	t.join();
	return EXIT_SUCCESS;
}  

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值