Since I’ve a strong belief that “doing it yourself is the best way to learn” so without going into the theory of multithreading (that I am sure you can learn elsewhere), I would like to put down steps to use boost library and make your first “threads” in C++.
For this article I am using visual studio 2010 (express), other multiplatform IDE’s such as code::blocks and eclipse for C++ can also be used following similar steps.
The desired output of this exercise is to setup the boost environment, setup a project in visual studio with the boost dependencies and most importantly to make a couple of threads in C++.
- Download the latest version of Boot library from http://www.boost.org/users/download/#releases
- Install Boost, I have installed it to “C:\boost_1_46_1”, which looks a like figure-1.
- Assuming that visual studio 2010 (express) is already installed, make a new Win32 console application and create an empty project. I’ve named my project as simpleBoostThreads.
- Now to setup the Boost library’s include paths right click on the project name and click on properties. On the property page click on “Configuration Properties” ->”C/C++” ->”General”. In the additional Include Directories field add the path of the library in my case it is “C:\boost_1_46_1\”. It should look like as in figure-2
- The last step in setting up the boost library is to add the library to the linker. To do that go to “Configuration Properties” ->”Linker” ->”General”. In the “Additional Library Directories” field add the path of the library in my case it is “C:\boost_1_46_1\lib”. It should look like as in figure-3
- Now add a new file main.cpp file in your project and write the following code snippet. It should look like in figure-4.
#include < iostream >
#include < boost/thread.hpp >
using namespace boost;
using std::cout;//adding the ostream's cout object from the std namespace
cout<<"This is the first thread\n";
cout<<"This is the second thread\n";
thread th1(&thread1), th2(&thread2);
- Now execute the program, and voila you have your first thread’s duo.
Download the project (open it up in Visual Studio 2010 and compile, make sure the boost paths are changed according to your PC)
This is my first article about multithreading using Boost library. I am hoping to contribute more by writing about more practical issues while using boost library in real projects.