std::thread 学习初步

标准库(C++0x)中的 thread 用起来似乎蛮简单的。

例子

一个 std::thread 对象可以接收

  • 普通的函数
  • 函数对象
  • 类的成员函数
  • lambda 函数

作为参数。

#include <QtCore>
#include <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;
    }
};
  • 以及lambda函数
  • 主程序
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    std::thread t1(test1);
    std::thread t2(test2, "test 2");
    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");
    std::thread t7([](const QString & text){qDebug()<<"hello"<<text;}, "test7");
    return a.exec();
}

备忘

  • 添加了两层括号(不然会被编译器认作一个名为t3的函数的声明)

    std::thread t3((Test3()));
  • std::bind ? 带参数,比如:

    std::thread t2(test2, "test 2");

要写成

    std::thread t2(std::bind(test2, "test 2"));

那一个标准?

  • std::ref ? (函数对象,或者参数,都是传值,传引用需要使用std::ref),比如对前面的Test3

    Test3 test3;
    test3();
    std::thread t3(test3);
    std::thread t33(std::ref(test3));

这三次调用的结果(类似于):

hello test3 0xbfc3b27f 
hello test3 0xbfc3b27f 
hello test3 0x9811e60 

参考


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值