Sunday, April 10, 2011

Begining multithreaded programming in boost

Hi,

With boost dev environment successfully installed, I now am embarking on the path to multi threaded nirvana.

For starters am going to paste the most basic multi threaded code here and the instructions how to build it.

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


using namespace std;

void workerFunc()
{

cout<<"workerFunc Started"<<endl;
boost::posix_time::seconds sec(3);
boost::this_thread::sleep(sec);
cout<<"workerFunc Finished"<<endl;
}

int main ( int argc, char * argv[])
{

cout<<"main started"<<endl;
boost::thread workerThread(workerFunc);
cout<<"main : waiting for workerThread"<<endl;
workerThread.join();
cout<<"main finished"<<endl;
return 0;

}
The code posted above is the most basic multi threaded code in boost, I will first explain the code and then post the instructions on how to compile it.

The code comprises of two functions.

1. workerFunc
2. main

We will be discussing only those lines which are relevant to threading.

In the workerFunc function two lines are of interest.

1. boost::posix_time::seconds sec(3)
2. boost::this_thread::sleep(sec)

In the first line a time construct named sec is defines with 3 as its value, it is defined in boost/date_time.hpp

The second line makes use of sleep function from boost::this_thread, it pause the execution of the current thread for the time provided as an argument to the sleep function. The handle/reference to the current thread is provided by boost::this_thread.

In the main function , again there are two lines which are of interest.

1. boost::thread wokerThread(workerFunc)
2. workerThread.join()

Line 1 creates a thread named workerThread and passes the name of the function to be executed in the newly created thread.

Line 2 uses the join function to instruct the main thread to wait for the new thread to finish execution.

Now , to compile the program the command is

g++ -o appName main.cpp -L /path/to/boost/lib -lboost_thread

g++ is the c++ compiler bundled with gcc, -0 flag tells the compiler to generate the executable with the supplied name, in our case appName, -L instructs the compiler to add the provided path to its search directories for libraries and finally -l flag is immediately followed by the library name.

The method we have used to supply the function to be executed as thread is not the only one, we can have thread functions which take arguments, have a class with thread function inside it etc etc.

Will explain other methods of creating and using threads using boost libraries as i delve deeper into the library.

Regards,
Ishan

No comments:

Post a Comment