c++11的多线程支持一(线程启动)
2014-01-13 13:28
447 查看
支持多线程编程,是c++11的一个新特性。在语言层面编写多线程程序,程序的可移植性得到很大提高。
新的线程库通过std::thread管理线程的执行,启动线程的方式有两种:
1、以一个函数地址为参数,实例化一个std::thread对象;
2、通过一个类的实例构造一个std::thread对象,用于构建std::thread的类必须实现了operator()方法。
一旦传入的函数返回,线程终止。下面以一个实例说明:
method one: start test thread
method one: thread start
method one: thread stop
method one: over
method two: start test thread
method two: thread start
method two: thread stop
method two: over
新的线程库通过std::thread管理线程的执行,启动线程的方式有两种:
1、以一个函数地址为参数,实例化一个std::thread对象;
2、通过一个类的实例构造一个std::thread对象,用于构建std::thread的类必须实现了operator()方法。
一旦传入的函数返回,线程终止。下面以一个实例说明:
#include <iostream> #include <thread> void fun() { std::cout << "method one: thread start" << std::endl; std::cout << "method one: thread stop" << std::endl; } class run { public: void operator()() { std::cout << "method two: thread start" << std::endl; std::cout << "method two: thread stop" << std::endl; } }; int32_t main() { // one method of launching thread std::thread t_1(fun); std::cout << "method one: start test thread" << std::endl; t_1.join(); std::cout << "method one: over" << std::endl; // the other method of launching thread run r; //std::thread t_2(r); // 1. this actually copies the supplied object into the thread. std::thread t_2(std::ref(r)); // 2. if you want to use the object you supplied, you can do so by wrapping it in std::ref. std::cout << "method two: start test thread" << std::endl; t_2.join(); std::cout << "method two: over" << std::endl; return 0; }执行后,这段代码的输出为:
method one: start test thread
method one: thread start
method one: thread stop
method one: over
method two: start test thread
method two: thread start
method two: thread stop
method two: over
相关文章推荐
- python多线程编程: python对多线程的支持和线程的创建、启动、挂起、退出
- c++11的多线程支持二(线程参数)
- 马士兵J2SE-第九章-多线程机制-线程的创建与启动
- C++多线程框架(一)--------- new一下就启动一个线程
- JAVA 多线程摘要--线程启动
- 多线程(c++11)------创建线程
- 线程01:多线程之线程启动、参数、返回值
- C#笔记19:多线程之线程启动、参数、返回值
- 【Java 语言】Java 多线程 一 ( 线程启动 | 线程中断 )
- C#笔记19:多线程之线程启动、参数、返回值
- Java多线程方面的编程笔试题(通过实现Runnable接口启动线程)
- Java_多线程_创建及启动线程
- Java对多线程的支持(一) - Thread类、Runnable接口、Daemon线程、线程同步
- 1多线程的概述2多线程(创建多个线程实例,并启动多个线程)的实现方式,main主方法是单线程的4多线程的实现方式5多线程模拟火车站售票出现问题7线程的声明周期
- android系统中的多线程(一): 关于在android中启动线程以及线程间的交互
- Java多线程-(4)线程的创建、启动、Runnable和Thread
- C++11中的线程支持库(Thread support library)
- c++11 线程启动带参数的函数
- C++11启动线程的多种方式
- 初见Java多线程(二、线程的创建与启动)