Receive our weekly advanced programming tips for FREE
19.April
How to use threads in C++ new 0x standard
0
| 0 votes
Autor: bookkeeper
Chapter: C++
Tags:
c++

C++ will get a new update in 2011. One of the updates in native threads! Very easy to use!

Finally we can do stuff like:

#include <iostream>
#include <thread>

void func(){
 std::cout << "func.." << std::endl;
}

int main (int argc, char const* argv[])
{
    std::thread t(func);
    t.join();
    return 0;
}

To compile this you need at least gcc 4.3, and you have to turn -std=c++0x on

g++ -Wall -std=c++0x -o thread thread.cpp

 NOTE: if you get "Segmentation fault" compile with: 

g++ -Wall -L/usr/lib -lpthread -pthread -std=c++0x -o thread thread.cpp

To use class method you need to give the thread constructor the method and class pointer

#include <iostream>
#include <thread>

class Hello{

 std::thread m_thread;

 public:
   Hello(){}
  ~Hello(){}
  void start(){
        m_thread = std::thread(&Hello::func, this);
  }
  void func(){
    while(true)
    {
        std::cout << "Hello Programmersbook.com" << std::endl;
        sleep(1);
    }
  }
  void join(){
    m_thread.join();
  }

};


int main (int argc, char const* argv[])
{
    Hello h;
    h.start();
    h.join();

    return 0;
}

Compile: g++ -Wall -L/usr/lib -lpthread -pthread -std=c++0x -o thread thread.cpp

Have fun!