C++ Boost Thread














































C++ Boost Thread



 Description: 

Boost thread library is allows the usage and implementation of threads in programs. Threads are used for faster execution of different functions simultaneously. These threads can are executed individually and generate distinct outputs.

 Program: 

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

boost::mutex mutex;

void span(int seconds)
{
  boost::this_thread::sleep_for(boost::chrono::seconds{seconds});
}


void testthread()
{
  using boost::this_thread::get_id;
  
  for (int i = 1; i <=5; i++)
  {
    span(1);
    mutex.lock();
    std::cout << "Thread id " << get_id() << ": " << i << std::endl;
    mutex.unlock();
  }
}

int main()
{
  boost::thread thread1{testthread};
  boost::thread thread2{testthread};
  thread1.join();
  thread2.join();
}

 Explanation: 

Header files: In this program we use 2 header files, <thread.hpp> to creating and executing threads and <chrono.hpp> for                                                generating time delays in outputs.

mutex class: mutex class is used to synchronize threads so that threads do not override ownership of other thread. This means that                                  if mutex is removed output will be mixed and threads will be executed randomly. mutex assures that while a thread                                    has lock on mutex all other threads have to wait till the thread unlocks mutex.

span function: span() is used to create time delay of 1 second between output.
                           (Removal of span() will not affect the output of the program)

testthread function: testthread() is used to define the task of a thread. This function can be different for different threads. In the                                              above program we assign the thread a task to print number from 1 to 5. Each time a thread is executed it 
                                      has to lock the mutex first and release it once the task is completed

main function: We create 2 threads name thread1 and thread2 and assign them task testthread.(Note that this task can be 
                            different for both the threads as well). We then execute both the threads using join().
 Output: 


More Articles of Suchit Gupta:

Name Views Likes
C++ Program to Convert Binary Number to Decimal and vice-versa 912 0
C++ Boost Thread 586 0

Comments