0

I'm trying to create a thread from a method that is in the same class as where I'm creating it from.

I have a class called Base that holds a method called Receive(). From the constructor of the Base() class I try to start a new thread that starts the Receive() method.

I tried like this:

std::thread receiveThread(Receive)

but for some reason it throws the error I wrote in the title. It also says "use '&NetworkingLib::Base::Receive' to create a pointer to member" but when I do that (it does compile) the thread crashes with an abort() error. You might need to know that Receive() does not need arguments and it returns nothing.

Any help appreciated. I can post more code if required.

pavel
  • 26,538
  • 10
  • 45
  • 61
Dries
  • 995
  • 2
  • 16
  • 45
  • You write "I can post more code if required." but "more" would imply that you had posted some code already :) – Sebastian Mach Jul 21 '14 at 12:13
  • `Receive` needs an object to work with, just like any other member function. – chris Jul 21 '14 at 12:13
  • Well I wrote how I wanted to start the thread itself :) so that's code (although not much and I understand what you're saying) – Dries Jul 21 '14 at 12:14
  • Chris, so what would you suggest as an "object" in this case? Should I just use "this" as an object? – Dries Jul 21 '14 at 12:14
  • We at least need to see what type of member function `Receive` is, and which object it's being called on (if it's not static). If you're calling this from the base constructor, and the function is virtual (or calls a virtual function, or otherwise accesses derived class members), and is invoked on the object being constructed, then you've got a race condition, since the object isn't fully constructed when the thread starts. – Mike Seymour Jul 21 '14 at 12:16
  • 2
    @Dries, I can't possibly know that. Pick an object appropriate for how the thread uses it. If `Receive` doesn't use `this`, make the function static or not a member function. – chris Jul 21 '14 at 12:17
  • Hi Mike, " void Base::Receive() " this is the method I want to start in a thread. Nothing more. It's a method in the same class I want to start it from – Dries Jul 21 '14 at 12:17
  • Is `receiveThread` a local variable? If that's the case, then the program will terminate when it's destroyed, unless you've joined or detached it. You probably want it to be a class member, so that you can leave it running and join it when it's time to stop. – Mike Seymour Jul 21 '14 at 12:20
  • So I tried it... But it still crashes. http://imgur.com/QRht7Wh -> this is a link to a screenshot of the callstack. I don't know if it's of any use – Dries Jul 21 '14 at 12:27

0 Answers0