天天看點

C++11并發程式設計3------線程傳參

/*
基本類型傳值
*/
#include <iostream>
#include <thread>

void func(int num)
{
    num = 100;
    std::cout << "func: " << num << std::endl;
}

int main()
{
    int num = 10;
    std::thread my_job(func, num);
    my_job.join();

    std::cout << "main: " << num << std::endl;
    return 0;
}      
/*
基本類型傳引用
*/
#include <iostream>
#include <thread>

void func(int &num)
{
    num = 100;
    std::cout << "func: " << num << std::endl;
}

int main()
{
    int num = 10;
    std::thread my_job(func, std::ref(num));
    my_job.join();

    std::cout << "main: " << num << std::endl;
    return 0;
}      
/*
類類型傳值
*/
#include <iostream>
#include <thread>

class A
{
public:
    int num_;
    A(int num) : num_(num)
    {
        std::cout << "A(int num)" << std::endl;
    }
    A(const A &a) : num_(a.num_)
    {
        std::cout << "A(const A &a)" << std::endl;
    }
    ~A()
    {
        std::cout << "~A()" << std::endl;
    }
};

void func(A a)
{
    std::cout << "a.num_ = " << a.num_ << std::endl;
    a.num_ = 100;
}

int main()
{
    A a(10);
    std::thread my_job(func, a);
    my_job.join();

    std::cout << "main : a.num_ = " << a.num_ << std::endl;
    return 0;
}      

類類型傳值執行結果:多次調用拷貝構造函數,影響效率,是以不推薦這種做法

/*
類類型傳引用
*/
#include <iostream>
#include <thread>

class A
{
public:
    int num_;
    A(int num) : num_(num)
    {
        std::cout << "A(int num)" << std::endl;
    }
    A(const A &a) : num_(a.num_)
    {
        std::cout << "A(const A &a)" << std::endl;
    }
    ~A()
    {
        std::cout << "~A()" << std::endl;
    }
};

void func(A &a)
{
    std::cout << "a.num_ = " << a.num_ << std::endl;
    a.num_ = 100;
}

int main()
{
    A a(10);
    std::thread my_job(func, std::ref(a));
    my_job.join();

    std::cout << "main : a.num_ = " << a.num_ << std::endl;
    return 0;
}      

 如果希望子線程裡面不修改對象的内容,形參可加const修飾。

/*
傳智能指針
*/
#include <iostream>
#include <thread>

void func(std::unique_ptr<int> int_ptr)
{
    std::cout << *int_ptr << std::endl;
}

int main()
{
    std::unique_ptr<int> int_ptr(new int(10));

    std::thread my_job(func, std::move(int_ptr));
    my_job.join();

    return 0;
}