c++11的多线程支持二(线程参数)

std::thread支持为线程传入参数,且支持任意类型、任意数目的参数。参数传入方式如下所示:

#include <iostream>
#include <string>
#include <vector>
#include <thread>

void fun(int32_t n, std::string str, std::vector<std::string> vec)
{
    std::cout << "method one: thread start" << std::endl;
    std::cout << "first input parameter is: " << n << std::endl;
    std::cout << "second input parameter is: " << str << std::endl;
    std::cout << "third input parameter is: [";
    for(std::vector<std::string>::const_iterator it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << ", ";
    }
    std::cout << "]" << std::endl;
    std::cout << "method one: thread stop" << std::endl;
}

class run
{
public:
    void operator()(int32_t n, std::string str, std::vector<std::string> vec)
    {
        std::cout << "method two: thread start" << std::endl;
        std::cout << "first input parameter is: " << n << std::endl;
        std::cout << "second input parameter is: " << str << std::endl;
        std::cout << "third input parameter is: [";
        for(std::vector<std::string>::const_iterator it = vec.begin(); it != vec.end(); it++)
        {
            std::cout << *it << ", ";
        }
        std::cout << "]" << std::endl;
        std::cout << "method two: thread stop" << std::endl;
    }
};

int32_t main()
{
    // one method of launching thread
    std::thread t_1(fun, 10, "test one", std::vector<std::string>(3, "one"));
    std::cout << "method one: start test thread" << std::endl;
    t_1.join();
    std::cout << "method one: over" << std::endl << std::endl;

    // the other method of launching thread
    run r;
    std::thread t_2(std::ref(r), 20, "test two", std::vector<std::string>(3, "two"));
    std::cout << "method two: start test thread" << std::endl;
    t_2.join();
    std::cout << "method two: over" << std::endl;
    return 0;
}

输出为:

method one: start test thread
method one: thread start
first input parameter is: 10
second input parameter is: test one
third input parameter is: [one, one, one, ]
method one: thread stop
method one: over


method two: start test thread
method two: thread start
first input parameter is: 20
second input parameter is: test two
third input parameter is: [two, two, two, ]
method two: thread stop
method two: over

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值