On Monday, October 22, 2012 12:50:52 AM UTC+2, ivan.po...@gmail.com wrote:
> If the thread function (the first argument to std::thread, threadMain below) takes a reference parameter, the code doesn't work as expected unless one calls the constructor with std::ref surrounding the variable (see below).
>
>
>
> Is this "by design"? I am using g++ 4.6.3 on Ubuntu.
>
>
>
> #include <iostream>
>
> #include <thread>
>
> #include <cstdint>
>
> #include <vector>
>
> #include <iterator>
>
>
>
> int count = 0;
>
>
>
> void threadMain( int threadId, int & counted )
>
> {
>
> while( count < 1000000 )
>
> {
>
> ++count;
>
> ++counted;
>
> }
>
> }
>
>
>
> int
>
> main( )
>
> {
>
> int counted1 = 0;
>
> int counted2 = 0;
>
>
>
> // std::thread t1( threadMain, 1, std::ref( counted1 ) );
>
> std::thread t1( threadMain, 1, counted1 );
>
>
>
> t1.join();
>
>
>
> std::cout << counted1 << ", " << counted2 << ", " << counted1 + counted2 << std::endl;
>
>
>
> return 0 ;
>
> }
>
>
>
> // to build: g++ -O3 -std=c++0x -pthread -o test test6.C
Generally, for threads it is safer to accept arguments by
value than by reference. The possibility always exists
that the spawning thread doesn't exist when the spawned thread
starts. Hence, it is better that the user makes explicit when
he wants it to be a reference (else what is referred to might
be gone...).
Hope this makes sense.
Regards,
Werner
|