Sunday, September 13, 2015

C++11 Thread Example

[thread1.c++]

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

void funThread1() {
    for (int i = 0; i < 10; ++i) {
        this_thread::sleep_for(chrono::seconds(1));
        cout<<"Thread-1"<<endl;
    }
}

void funThread2() {
    for (int i = 0; i < 10; ++i) {
        this_thread::sleep_for(chrono::seconds(1));
        cout<<"Thread-2"<<endl;
    }
}

void funThread3() {
    for (int i = 0; i < 10; ++i) {
        this_thread::sleep_for(chrono::seconds(1));
        cout<<"Thread-3"<<endl;
    }
}

int main() {
  thread t1(funThread1);
  thread t2(funThread2);
  thread t3(funThread3);

  cout<<"Main Function - wait for Threads to complete ..."<<endl;

  t1.join();
  t2.join();
  t3.join();

  return 0;
}

Compilation:
g++ -o thread1 thread1.c++ -std=c++11 -lpthread

No comments:

Post a Comment