C++11 中std::thread和std::mutex的用法

6 篇文章 0 订阅

关于线程,之前用的最多的就是C语言的 pthread 系列函数;
QT中也有QThread 类可以直接用。
偶然发现C++11 中早已经拥有了一个更好用的线程类std::thread
下面简单介绍一下std::thread的基本用法吧

#include <thread>
bool HelloWorld::init()
{
    std::thread t1(&HelloWorld::firstThread,this);//创建一个分支线程,回调到firstThread函数里

    t1.join(); //等待子线程firstThread执行完之后,主线程才可以继续执行下去,此时主线程会释放掉执行完后的子线程资源

    //线程可传参
    std::thread t2(&HelloWorld::secondThread,this,10,20);//创建一个分支线程,回调到secondThread函数里

    t2.detach(); //将子线程从主线程里分离,子线程执行完成后会自己释放掉资源; 分离后的线程,主线程将对它没有控制权

    LOG("in major thread");//在主线程

    return true;
}

void HelloWorld::firstThread()
{
    LOG("in first thread");//在子线程
}

void HelloWorld::secondThread(int first,int second)
{
    LOG("in second thread,first = %d,second = %d",first,second);
}

初始化互斥锁

std::mutex mutex;//线程互斥对象

mutex.lock(); //加锁
mutex.unlock(); //解锁
这里就不写例子解释锁的用法了。


各种std::thread调用的用法例子:

void test1()
{
    qDebug()<<"hello test 1";
}
void test2(const QString &text)
{
    qDebug()<<"hello"<<text;
}
class Test3
{
public:
    Test3(){}
    void operator()() const
    {
        qDebug()<<"hello test3"<<this;
    }
};
class Test4
{
public:
    QString a;
    Test4(const QString a):a(a){}
    void operator()(const QString b) const
    {
        qDebug()<<a<<b;
    }
};
class Test5
{
public:
    void output()
    {
        qDebug("hello test 5");
    }
};

class Test6
{
public:
    void output(const QString & text)
    {
        qDebug()<<"hello"<<text;
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //普通的函数
    std::thread t1(test1);
    //std::thread t2(std::bind(test2, "test 2"));
    std::thread t2(test2, "test 2");
    //添加了两层括号(不然会被编译器认作一个名为t3的函数的声明)
    std::thread t3((Test3()));
    //函数对象
    std::thread t4(Test4("hello"), "test 4");
    //类的成员函数
    Test5 test5;
    std::thread t5(&Test5::output, &test5);
    Test6 test6;
    std::thread t6(&Test6::output, &test6, "test 6");
    //lambda函数
    std::thread t7([](const QString & text){qDebug()<<"hello"<<text;}, "test7");
    return a.exec();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值