Polar Bear
Polar Bear

Reputation: 169

Thread join() referencing class member

I am trying to create a Sender class that instantiates thread objects that have a certain workflow (SenderWorkflow), but I am having an issue with calling the default methods found on the std::thread library, specifically the std::thread::join() method.

The compiler is complaining about the following error:

a nonstatic member reference must be relative to a specific object

How can I call the join function for a specific object of class Sender?

//sender.h
#include <iostream>
#include <thread>

class Sender {
public:

    static bool isFinished;

    Sender() //sender constructor creates a sender thread object
    {
        std::thread worker(Sender);
    }

    void SenderWorkflow();

    void join() {
        std::thread::join();
    }

};
//main.cpp
#include <iostream>
#include <thread>
#include "Sender.h"

int main()
{
    Sender mSender; //Create thread object for worker
    Sender::isFinished = true; //
    mSender.join(); //wait for the worker thread to finish execution
}
//sender.cpp
#include <iostream>
#include <thread>
#include "Sender.h"

void Sender::SenderWorkflow()
{
    while (!Sender::isFinished)
    {
        std::cout << "Working... \n";
    }
}

Upvotes: 0

Views: 346

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36498

worker isn't a member of Sender, its a local variable. If it was a member you could just do worker.join():


class Sender {
public:

    static bool isFinished;
    std::thread worker;
    
    Sender()
    : worker(&Sender::SenderWorkflow, this)
    {
    }

    void SenderWorkflow();

    void join() {
        worker.join();
    }

};

Note that your syntax for creating a thread which calls SenderWorkflow was incorrect too.

As isFinished is used from multiple threads it should be static std::atomic<bool> isFinished to help avoid data races.

Upvotes: 1

Related Questions