User Tools

Site Tools


c:c_threads:create_a_thread:create_a_thread_with_a_class_object

C - C++ Threads - Create a thread - Create a thread with a class object

Create a class object and pass it to the thread constructor.

#include <iostream>
#include <thread>
 
// Create the class.
class Messages
{
public:
  void operator() () const
  {
    std::cout << "Hello World" << std::endl;
  }
};
 
int main()
{
  Messages msg;
  thread t1(msg);
  t1.join();
  return 0;
}

Using a class function

#include <iostream>
#include <thread>
 
class Messages
{
public:
  void ShowMessage()
  {
    std::cout << "Hello World" << std::endl;
  }
};
 
int main()
{
  // Execute the ShowMessage() method for a specific Message class object on a separate thread.
  Message msg;
  std::thread t1(&Messages::ShowMessage, &msg);
  t1.join();
  return 0;
}

NOTE: Here the ShowMessage() method is being executed for a specific Message object on a separate thread.

If other threads are accessing the same “msg” object, the shared resources of that object will need to protected with a mutex.


Main Thread starts 10 Worker Threads and after starting all these threads, the main function will wait for them to finish.

After joining all the threads main function will continue,

#include <iostream>
#include <thread>
#include <algorithm>
 
class WorkerThread
{
public:
  void operator()()
  {
     std::cout<<"Worker Thread "<<std::this_thread::get_id()<<" is Executing"<<std::endl;
  }
};
 
int main()
{
  std::vector<std::thread> threadList;
  for(int i = 0; i < 10; i++)
  {
    threadList.push_back(std::thread(WorkerThread()));
  }
 
  // Now wait for all the worker thread to finish i.e.
  // Call join() function on each of the std::thread object
  std::cout<<"wait for all the worker thread to finish"<<std::endl;
  std::for_each(threadList.begin(),threadList.end(), std::mem_fn(&std::thread::join));
  std::cout<<"Exiting from Main Thread"<<std::endl;
 
  return 0;
}
c/c_threads/create_a_thread/create_a_thread_with_a_class_object.txt · Last modified: 2021/03/05 16:36 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki