erik321123
erik321123

Reputation: 55

How to do c++ multithreading in a class (keep thread ref as member var)

So I am trying do do some multithreading in c++, I am trying to use the std::thread. All examples I can find on the internet use the main method. But I want to create a thread in a class constructor, and join the thread in the destructor and then clean up the thread. I have tried several things like this:

.cpp:

#inlcude "iostream"
myClass::myClass()
{
    myThread= new std::thread(threadStartup, 0);
}

myClass::~myClass()
{
    myThread->join();
    delete myThread;
}

void threadStartup(int threadid) 
{
    std::cout << "Thread ID: " << threadid << std::endl;
}

.h

#pragma once
#include "thread"
class myClass 
{
public: 
    myClass();
    ~myClass();
private:
    std::thread* myThread;
};

This gives me the following error error: C2065: 'threadStartup': undeclared identifier. I have also tried to add the thread startup method to the class, but that gives me a whole lot more errors.

I cant figure this out, any help would be appreciated.

EDIT: std::thread has been changed to std::thread* like in my code. If I move the function declaration of threadStartup to the top of my file I get the errors:

Severity    Code    Description Project File    Line    Suppression State
Error   C2672   'std::invoke': no matching overloaded function found

And

Severity    Code    Description Project File    Line    Suppression State
Error   C2893   Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'   

Upvotes: 0

Views: 591

Answers (2)

doron
doron

Reputation: 28932

C++ is parsed top down ans since your threadStartup function is declared after you use it, the compiler cannot find it. Declare threadStartup before you use it and you should be ok.

Upvotes: 0

Scheff&#39;s Cat
Scheff&#39;s Cat

Reputation: 20161

Cannot reproduce. Please, see my sample code test-thread.cc:

#include <iostream>
#include <thread>

class MyClass {
  private:
    std::thread myThread;
  public:
    MyClass();
    ~MyClass();
};

void threadStartup(int threadid)
{
  std::cout << "Thread ID: " << threadid << std::endl;
}

MyClass::MyClass():
  myThread(&threadStartup, 0)
{ }

MyClass::~MyClass()
{
  myThread.join();
}

int main()
{
  MyClass myClass;
  return 0;
}

Tested in cygwin64 on Windows 10 (64 bit):

$ g++ --version
g++ (GCC) 5.4.0

$ g++ -std=c++11 -o test-thread test-thread.cc 

$ ./test-thread
Thread ID: 0

$

Please, notice that I don't use new (as its not necessary in this case).

Upvotes: 1

Related Questions