O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.1. Creating a Thread

Problem

You want to create a thread to perform some task while the main thread continues its work.

Solution

Create an object of the class thread, and pass it a functor that does the work. The creation of the thread object will instantiate an operating system thread that begins executing at operator() on your functor (or the beginning of the function if you passed in a function pointer instead). Example 12-1 shows you how.

Example 12-1. Creating a thread

#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>

struct MyThreadFunc {
   void operator()() {
      // Do something long-running...
   }
} threadFun;

int main() {

   boost::thread myThread(threadFun); // Create a thread that starts
                                      // running threadFun

   boost::thread::yield(); // Give up the main thread's timeslice
                           // so the child thread can get some work
                           // done.

   // Go do some other work...

   myThread.join(); // The current (i.e., main) thread will wait
                    // for myThread to finish before it returns

}

Discussion

Creating a thread is deceptively simple. All you have to do is create a thread object on the stack or the heap, and pass it a functor that tells it where it can begin working. For this discussion, a "thread" is actually two things. First, it's an object of the class thread, which is a C++ object in the conventional sense. When I am referring to this object, I will say "thread object." Then there is the thread of execution, which is an operating system thread that is represented by the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required