官方例子

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <unistd.h>

using namespace std;

void foo() 
{
        // do stuff...
        for(int i = 0 ; i < 10 ; ++i){
                cout << i << endl;
                sleep(1);
        }
}

void bar(int x)
{
        // do stuff...
        for(int i = 0 ; i < 10 ; ++i){
                cout << i << endl;
                sleep(1);
        }
}

int main() 
{
        std::thread *first = new thread(bar,2);     // spawn new thread that calls foo()
        std::thread second (bar,0);  // spawn new thread that calls bar(0)

        std::cout << "main, foo and bar now execute concurrently...\n";

        // synchronize threads:
        first->join();                // pauses until first finishes
        second.join();               // pauses until second finishes

        delete first;
        std::cout << "foo and bar completed.\n";
        return 0;
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-23
  • 2021-09-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-03
  • 2022-12-23
  • 2022-03-07
  • 2021-06-21
  • 2021-05-26
  • 2021-12-15
  • 2022-02-28
相关资源
相似解决方案