0

I'm trying to use std::thread in c++ without success:

A.h

class A
{
   public:
      A();
      void MainThread();
      Init();

   private:
      std::thread currThread;
}

A.cpp

A::A()
{

}


void A::Init()
{
    currThread = std::thread(A::MainThread); 
    //currThread = std::thread(&MainThread);
}

void A::MainThread()
{
    while (true)
    {
        std::cout << "Just For Example...");
    }
}

I'm getting compilation error in the Init function when trying to create the thread with the MainFunction

What am I doing wrong and how can I fix it ?

  • Pass this as argument. – Hatted Rooster Jan 12 '17 at 08:26
  • Read up on member function pointers etc, see http://stackoverflow.com/questions/10673585/start-thread-with-member-function. Also are you *sure* you need aseperate Init function and not just construct the thread in the constructor's initializer list? And should MainThread really be public? – stijn Jan 12 '17 at 08:29

1 Answers1

0

Since the MainThread() method is not static, it will exist many times for different objects, so you need to indicate that you are referring to the method that belongs to this object (the object that you are calling Init() on).

There are many worrying things about your code (syntax error, infinite loop, etc.). Your example code (with the fix) should look something like this:

// A.hpp
#ifndef A_HPP
#define A_HPP

#include <thread>

class A
{
   public:
      void Init();
      void MainThread();

   private:
      std::thread currThread;
};

#endif // A_HPP

// A.cpp
#include <iostream>
#include <thread>
#include "A.h"

void A::Init()
{
    this->currThread = std::thread(&A::MainThread, this);
}

void A::MainThread()
{
    //this loop will run forever
    while (true)
    {
        std::cout << "Just For Example...";
    }
}
  • it still doesnt work. the compiler does not like the code line: "this->currThread = std::thread(&A::MainThread);" I'm getting error: error: class "std::result_of ()>" has no member "type" –  Jan 12 '17 at 11:42
  • Try this->currThread = std::thread(&A::MainThread, this); – Abdulrahman Alhadhrami Jan 12 '17 at 12:12