C++0x之高并发【线程运行管理】

本文介绍了如何使用C++标准库中的std::thread来管理线程,包括启动线程、等待线程完成、线程控制权转移及运行时监控。通过具体示例展示了如何创建线程并传递不同类型的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 线程的启动

std::thread可以与任何可调用类型一同工作】所以可以传递函数,lamda表达式,带有函数操作符的类实例等进行构造thread。

#include <iostream>
#include <functional>
#include <thread>
#include <string>
using namespace std;

void call_fun(int n)
{
    //for(int i=0;i<100;i++)
    {
        cout<<n<<endl;
    }
}

class test
{
public:
    void operator()()
    {
        cout<<"Class::operator"<<endl;
    }

};


int main(int argc, char *argv[])
{
    std::thread th_fun(call_fun,123);
    th_fun.join();

    std::thread th_lamda([]{cout<<"lamda function"<<endl;});
    th_lamda.join();

    std::thread th_class_operator((test()));
    th_class_operator.join();

    return 0;
}

 等待线程完成

【使用join等待线程运行完成,注意异常情况下的等待】

#include <iostream>
#include <functional>
#include <thread>
#include <string>
#include <stdio.h>

using namespace std;

void calc_fun(int n)
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        sum+=i;
    }
    cout<<"calc ret:"<<sum<<endl;
}


class thread_guard
{
public:
    thread_guard(const thread_guard&)=delete;
    thread_guard& operator =(const thread_guard&)=delete;
    explicit thread_guard(std::thread& __t):__th(__t)
    {

    }
    ~thread_guard()
    {
        if(__th.joinable())
        {
            __th.join();
        }
    }
private:
    std::thread& __th;
};


int main(int argc, char *argv[])
{
    thread th1(calc_fun,10000000);
    //th1.join();
    thread_guard t(th1);
    return 0;
}

线程转移控制权

#include <iostream>
#include <functional>
#include <thread>
#include <string>
#include <stdio.h>

using namespace std;

void calc_fun(int n)
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        sum+=i;
    }
    cout<<"calc ret:"<<sum<<endl;
}


int main(int argc, char *argv[])
{
    thread th1(calc_fun,10000);
    thread th2 = std::move(th1);
    th1.joinable()?th1.join(),1:printf("Th1 can not Join\n");
    th2.joinable()?th2.join(),1:printf("Th2 can not Join\n");
    return 0;
}

运行时线程监控

#include <iostream>
#include <algorithm>
#include <thread>
#include <vector>
using namespace std;

void do_task()
{
    cout<<"Current thread ID:"<<this_thread::get_id()<<endl;
}

int main(int argc,char** argv)
{
    thread::id master_id = this_thread::get_id();
    //取线程数为cpu核心数的2倍
    unsigned int  thread_count = thread::hardware_concurrency();
    vector<std::thread> ths;
    for(int i=0;i<thread_count;i++)
    {
        ths.push_back(std::thread(do_task));
    }

    for(int i=0;i<thread_count;i++)
    {
        ths[i].join();
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值