您的位置:首页 > 编程语言 > C语言/C++

c++ 11 thread使用

2015-09-15 14:34 441 查看
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>

std::mutex mtx;

void foo()
{
    int i=0;
    while(i++<100)
    {
        mtx.lock();
        sleep(3);
        printf("foo %d\n",i);
        mtx.unlock();
        sleep(1);
    }
}

void bar(int x)
{
    int i=100;
    while(i++<200)
    {
        mtx.lock();
        printf("bar %d\n",i);
        mtx.unlock();
        sleep(1);
    }
}

int main()
{
  std::thread first (foo);     // 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";

  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: