c++11 thread类的简单使用

一个thread对象就代表一个线程执行,当对象创建完成后,线程函数就开始执行,下面这段话是c++11的thread类介绍。

An initialized thread object represents an active thread of execution; Such a thread object is joinable, and has a unique thread id.

A default-constructed (non-initialized) thread object is not joinable, and its thread id is common for all non-joinable threads.

A joinable thread becomes not joinable if moved from, or if either join or detach are called on them.

需要注意的是:当一个线程对象是joinable状态时,对象在析构前需要使用detach或者jion函数。

现在写代码证实这段话,加深c++11 thread类的使用,具体代码如下:

#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <thread>

void pause_thread(int nSleepTime)
{
    //std::cout << "pause for: " << nSleepTime << "\n";
    std::this_thread::sleep_for(std::chrono::seconds(nSleepTime));
}

int main()
{
    //thread1和thread2 是初始化的线程对象,它是joinable状态并且有唯一的id;
    std::thread thread1(pause_thread, 1);
    std::thread thread2(pause_thread, 2);

    //thread3是未初始化的线程对象,它是非joinable状态,id不唯一
    std::thread thread3;

    //验证代码
    if (thread1.joinable())
    {
        std::cout <<"thread1 is joinable" << std::endl;
    }
    if (thread2.joinable())
    {
        std::cout << "thread2 is joinable" << std::endl;
    }

    if (!thread3.joinable())
    {
        std::cout << "thread3 is not joinable" << std::endl;
    }

    std::cout << "***********分割线*****************\n\n" << std::endl;

    std::cout << "thread1: " << thread1.get_id() << std::endl;
    std::cout << "thread2: " << thread2.get_id() << std::endl;
    std::cout << "thread3: " << thread3.get_id() << std::endl;

    //thread objects that are joinable shall either be joined
    // or detached before they are destroyed.
    thread1.join();
    thread2.detach();

    std::cout << "*************分割线****************\n\n" << std::endl;

    //A joinable thread becomes not joinable if moved from, 
    //or if either join or detach are called on them.

    if (!thread1.joinable())
    {
        std::cout << "thread1 becomes not joinable" << std::endl;
    }
    if (!thread2.joinable())
    {
        std::cout << "thread2 becomes not joinable" << std::endl;
    }

    return 0;
}

运行结果:
这里写图片描述

参考资料:http://www.cplusplus.com/reference/thread/thread/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值