std::thread基本用法

1、创建和使用线程 

void showInfo()
{
    std::thread::id id = std::this_thread::get_id();//当前线程id
    debug "执行showInfo()" << std::hash<std::thread::id>()(id);
}
  • 创建线程对象时指定一个函数,在其他线程中运行此函数:

    std::thread t1{showInfo};
int main(int argc, char *argv[])
{
    std::thread t1{showInfo};
    std::thread t2{showInfo};

    t1.join();//等待线程运行
    t2.join();

    std::thread::id id1 = t1.get_id();
    std::thread::id id2 = t2.get_id();
    std::thread::id id = std::this_thread::get_id();//当前线程id

    debug std::hash<std::thread::id>()(id1);
    debug std::hash<std::thread::id>()(id2);
    debug std::hash<std::thread::id>()(id);
}

struct ceshi
{
    void operator () ()
    {
        debug "run ceshi";
    }
};

int main(int argc, char *argv[])
{
    std::thread t1{ceshi()};

    t1.join();//等待线程运行

    std::thread::id id1 = t1.get_id();
    debug std::hash<std::thread::id>()(id1);
}

2、传递参数

void showInfo(const QString & string)
{
    debug "执行showInfo() start";
    debug "当前线程id = " <<std::hash<std::thread::id>()(std::this_thread::get_id());
    debug string;
    debug "执行showInfo() end";
}

int main(int argc, char *argv[])
{
    std::thread t1{showInfo,"我是一个字符串11111"};
    t1.join();

    debug endl;

    std::thread t2{showInfo,"我是一个字符串22222"};
    t2.join();
}

当传递非const的引用时要加上std::ref(),否则可能编译失败:

void showInfo(QString & string)
{
    debug string;
}

int main(int argc, char *argv[])
{
    QString src = "我是一个字符串";
    std::thread t1{showInfo,std::ref(src)};
    t1.join();
}

3、在线程中执行成员函数

 静态成员函数可直接执行:

class test
{
public:
    test() = default;
    static void show()
    {
        qDebug()<<"hello";
    }
};

int main(int argc, char *argv[])
{
    std::thread thread1(&test::show);
    thread1.join();
}

非静态成员函数需要传入一个对象作为参数:

class test
{
public:
    test() = default;
    void show()
    {
        qDebug()<<"hello";
    }
};

int main(int argc, char *argv[])
{
    test t;
    std::thread thread1(&test::show,&t);
    thread1.join();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值