zoukankan      html  css  js  c++  java
  • 线程基础2

    #include <thread>
    void func()
    {
       // do some work
    }
    int main()
    {
       std::thread t(func);
       t.join();
       return 0;
    }

    带参数

    void func(int i, double d, const std::string& s)
    {
        std::cout << i << ", " << d << ", " << s << std::endl;
    }
    int main()
    {
       std::thread t(func, 1, 12.50, "sample");
       t.join();
       return 0;
    }
    #include <thread>
    #include <iostream>
    #include <string>
    #include <functional>
    
    void greeting(std::string const& message)
    {
        std::cout<<message<<std::endl;
    }
    
    int main()
    {
        std::thread t(std::bind(greeting,"hi!"));
        t.join();
    }

    传引用

    void func(int& a)     //这里参数声明要是引用形式
    {
        a++;
    }
    int main()
    {
        int a = 42;
        std::thread t(func, std::ref(a)); // 配合函数声明为引用形式,这两者同时存在,a的值才能改变。
        t.join();
        std::cout << a << std::endl;
        return 0;
    }

    线程调用:类重载()

    #include <thread>
    #include <iostream>
    class SayHello
    {
    public:
        void operator()() const
        {
            std::cout<<"hello"<<std::endl;
         std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    };
    int main()
    {
        std::thread t((SayHello()));
        t.join();
       SayHello hello;
        std::thread t1(hello);
        t1.join();
       std::thread t2=std::thread(SayHello());
         t2.join();

        std::thread t3{ SayHello() };
        t3.join();

    }

     线程调用:类成员函数:

    #include <thread>
    #include <iostream>
    # include <memory>
    
    class SayHello
    {
    public:
        void greeting() const
        {
            std::cout << "hello" << std::endl;
        }
        void good(std::string const& message) const
        {
            std::cout << message << std::endl;
        }
    
    };
    int main()
    {
        SayHello x;
        std::thread t(&SayHello::greeting, &x);
        std::thread t1(&SayHello::good, &x, "good");
        t.join();
        t1.join();
    
    
        std::shared_ptr<SayHello> p(new SayHello);
        std::thread t2(&SayHello::good, p, "goodbye");
        t2.join();
    }
  • 相关阅读:
    普通类型(Trivial Type)和标准布局类型(Standard-layout Type)以及POD类型
    设计模式
    网络相关的学习和命令总结
    sheel命令学习和工作总结。
    Makefile的学习
    [UI基础][实现]九宫格之应用程序管理
    [嵌入式][分享][交流]发布一个消息地图的模块
    [UI基础][不会说话的汤姆猫]
    [UI基础][QQ登陆界面]
    volatile的陷阱
  • 原文地址:https://www.cnblogs.com/yuguangyuan/p/5857821.html
Copyright © 2011-2022 走看看