User Tools

Site Tools


c:c_threads:create_a_thread:create_a_thread_with_a_class_object

This is an old revision of the document!


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(&Message::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.

c/c_threads/create_a_thread/create_a_thread_with_a_class_object.1614937666.txt.gz · Last modified: 2021/03/05 09:47 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki