1

So I tried to create a thread for two functions from a class that I made:

MessagesSender all;
    std::thread t1(all.updateMessages);
    std::thread t2(all.sendMessages);

But it says this error when I try to compile : non-standard syntax; use '&' to create a pointer to member

Why??

Hee hee
  • 33
  • 4

2 Answers2

1

you should be doing

std::thread t1(&MessagesSender::updateMessages, MessagesSender());
...
...
t1.join();

and likewise for any other member functions

If you want to be using the same object then pass the object by reference

std::thread t1(&MessagesSender::updateMessages, std::ref(myMessageSenderobj));
pcodex
  • 1,812
  • 15
  • 16
  • @Yksisarvinen Indeed, plus the current code is undefined behaviour as the temporary will be destroyed immediately. – Arthur Tacca Mar 13 '20 at 12:01
  • I have to use an object in the two of them with the same data.. – Hee hee Mar 13 '20 at 12:29
  • 1
    @Yksisarvinen I've updated my answer. – pcodex Mar 13 '20 at 20:19
  • 1
    @Arthur Tacca I don't agree that it would be undefined behavior. The arguments to the thread constructor are copied. – pcodex Mar 13 '20 at 20:20
  • Oops you are right, my mistake. Thanks for clarifying. (Actually it moves if it's an rvalue reference, as it is in this case, but the point is the same: it is instantiating am fresh object target than taking a reference to an existing one.) – Arthur Tacca Mar 14 '20 at 09:47
0

thread constructors:

thread( thread&& other ) noexcept;

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

thread(const thread&) = delete;

So:

... t1(&MessagesSender::updateMessages ...
Dr. Andrey Belkin
  • 795
  • 1
  • 9
  • 28