Error while executing a simple thread stream program

Could you tell mw what the problem is with the boost :: thread program below

#include<iostream> #include<boost/thread/thread.hpp> boost::mutex mutex; class A { public: A() : a(0) {} void operator()() { boost::mutex::scoped_lock lock(mutex); } private: int a; 

};

 int main() { boost::thread thr1(A()); boost::thread thr2(A()); thr1.join(); thr2.join(); 

}

I get the error message: error: request for member 'join' in 'thr1', which is of type non-class 'boost :: thread () (A () ())' BoostThread2.cpp: 30: error: request for member of 'join' in 'thr2', which is of type non-class 'boost :: thread () (A () ())'

+4
source share
2 answers

You stumbled upon something wonderfully known as the most unpleasant parsing . The quickest way to fix this is to add an extra set of parentheses:

 boost::thread thr1((A())); 

You can also enter a temporary:

 A tmp1; boost::thread thr1(tmp1); 

In the most unpleasant analysis, as you think, a temporary one is created, it is analyzed as if it does not take any parameters. Then it treats thr1 as a prototype of a function that takes one parameter (which is the function mentioned above) and returns boost :: thread.

+7
source

This is a classic C ++ trap. thr1 is not what you think (stream object). This is a declaration of a function that takes an instance of A as a parameter. Wrap it in parentheses to force the intended interpretation:

 boost::thread thr1((A())); boost::thread thr2((A())); 

Detailed explanation

The syntax of the original syntax is equivalent to:

 boost::thread thr1(A); 

Why does the compiler allow ignoring empty parentheses? Honestly, I'm not sure. I am not an expert in C ++ and - but I think this is due to the following thought: A *a = A (*a) , therefore A * = A (*) ; similarly, A a = A (a) , therefore A = A () .

Look to the future!

The upcoming C ++ standard will fix this as a byproduct of its new initialization syntax:

 boost::thread thr1{A()}; boost::thread thr2{A()}; 
+6
source

Source: https://habr.com/ru/post/1309845/


All Articles