0

This is my code:

    MessagesSender all;

std::thread t1(&MessagesSender::updateMessages,all);
    std::thread t2(&MessagesSender::sendMessages,all);
            all.signIn();
t1.join();
t2.join();

Inside the threads function there's a loop that keeps the thread running every sixty seconds. The sign in function changes one of the variables in 'all' but the threads ignore the change and don't update the object, as if I sent two different objects.

Here is my class:

class MessagesSender
{
public:
    void Menu();
    void signIn();
    void signOut();
    void showUsers();
    bool checkIfExist(std::string name);
    void updateMessages();
    void sendMessages();
protected:
    std::vector<std::string> users;
    std::queue<std::string> messages;
};

And the signIn function:

void MessagesSender::signIn()
{
    std::string name = "";
    std::cout << "Enter name\n";
    std::cin >> name;
    if (checkIfExist(name))
    {
        std::cout << "User already exists!\n";
    }
    else
    {
        users.push_back(name);
    }
}
Hee hee
  • 33
  • 4
  • 1
    Does this answer your question? [Passing object by reference to std::thread in C++11](https://stackoverflow.com/questions/34078208/passing-object-by-reference-to-stdthread-in-c11) – unlut Mar 13 '20 at 13:57

1 Answers1

1

With e.g.

std::thread t1(&MessagesSender::updateMessages,all);

you create the thread by using a copy of the all object.

When you modify the original all object the copies running the threads won't be modified.

You need to use a reference or a pointer when creating the thread:

std::thread t1(&MessagesSender::updateMessages,&all);

Also beware of data-races, you need to make sure that the member variables modified by signIn are protected, so the threads don't attempt to access them simultaneously.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621