菜鸟笔记
提升您的技术认知

c std::thread 线程的传参方式-ag真人游戏

c std::thread 线程的传参方式

flyfish

标准 c 11

传递一个函数的方式

#include 
#include 
void thread_function()
{
  
    std::cout << "thread function\n";
}
int main()
{
  
    std::thread t(&thread_function);   // t starts running
    std::cout << "main thread\n";
    t.join();   // 主线程等待线程t完成
    std::cout << "end\n";
    return 0;
}

柏拉图理念世界的样子

柏拉图可感世界的样子


结果

main thread
thread function
end

传值的方式

#include 
#include 
#include 
void thread_function(std::string s)
{
  
    std::cout << "t thread is = " << s << std::endl;
}
int main()
{
  
    std::string s = "abc";
    std::thread t(&thread_function, s);
    std::cout << "main thread message = " << s << std::endl;
    t.join();
    return 0;
}
main thread message = abc
t thread is = abc

传址的方式

#include 
#include 
#include 
void thread_function(std::string &s)
{
  
    std::cout << "t thread is = " << s << std::endl;
    s = "cde";
}
int main()
{
  
    std::string s = "abc";
    std::thread t(&thread_function, std::ref(s));
    t.join();
    std::cout << "main thread message = " << s << std::endl;
    return 0;
}

结果

t thread is = abc
main thread message = cde

在线程之间不共享内存(不复制)的方式

#include 
#include 
#include 
void thread_function(std::string s)
{
    std::cout << "t thread is = " << s << std::endl;
    s = "cde";
}
int main()
{
    std::string s = "abc";
    std::thread t(&thread_function, std::move(s));
    t.join();
    std::cout << "main thread message = " << s << std::endl;
    return 0;
}

结果

t thread is = abc
main thread message = 

函数对象的方式

#include 
#include 
class thread_obj {
  
public:
    void operator()(int x)
    {
  
        for (int i = 0; i < x; i  )
            std::cout << "thread using function object as callable\n";
    }
};
int main()
{
  
    std::thread th(thread_obj(), 3);
    th.join();
    return 0;
}

lambda 表达式的方式

#include 
#include 
int main()
{
  
    // define a lambda expression
    auto f = [](int x) {
  
        for (int i = 0; i < x; i  )
            std::cout << "thread using lambda expression as callable\n";
    };
    std::thread th(f, 3);
    th.join();
    return 0;
}

传递类的成员函数的方式

#include 
#include 
class sayhello
{
public:
    void greeting(std::string const& message) const
    {
        std::cout<

堆分配对象的方式

#include 
#include 
class sayhello
{
  
public:
    void greeting(std::string const& message) const
    {
  
        std::cout< p(new sayhello);
    std::thread t(&sayhello::greeting,p,"hello");
    t.join();
}

线程可移动构造 (moveconstructible) 或移动赋值 (moveassignable) ;

不可复制构造 (copyconstructible) 或复制赋值 (copyassignable)

#include 
#include 
void thread_function()
{
  
    std::cout << "t thread function\n";
}
int main()
{
  
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    std::thread t2 = std::move(t);
    t2.join();
    return 0;
}

结果

main thread
t thread function
网站地图