C++多线程的简单创建

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
 
void f1(int n)
{
    
    
    for (int i = 0; i < 5; ++i) {
    
    
        std::cout << "Thread 1 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
void f2(int& n)
{
    
    
    for (int i = 0; i < 5; ++i) {
    
    
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
class foo
{
    
    
public:
    void bar()
    {
    
    
        for (int i = 0; i < 5; ++i) {
    
    
            std::cout << "Thread 3 executing\n";
            ++n;
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }
    int n = 0;
};
 
class baz
{
    
    
public:
    void operator()()
    {
    
    
        for (int i = 0; i < 5; ++i) {
    
    
            std::cout << "Thread 4 executing\n";
            ++n;
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }
    int n = 0;
};
 
int main()
{
    
    
    int n = 0;
    foo f;
    baz b;
    std::thread t1; // t1 is not a thread
    std::thread t2(f1, n + 1); // 值传递
    std::thread t3(f2, std::ref(n)); // 引用传递
    std::thread t4(std::move(t3)); // t4运行t3,t3不再运行
    std::thread t5(&foo::bar, &f); // t5 在对象f上运行foo类的bar()函数
    std::thread t6(b); 
    // t6 在对象 b 的一个副本上运行baz类的operator()()函数
   //重载运算符(operator())
    t2.join();
    t4.join();
    t5.join();
    t6.join();
    std::cout << "Final value of n is " << n << '\n';
    std::cout << "Final value of f.n (foo::n) is " << f.n << '\n';
    std::cout << "Final value of b.n (baz::n) is " << b.n << '\n';
}

猜你喜欢

转载自blog.csdn.net/qq_40595787/article/details/120186163
今日推荐