Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should not std::thread::id default constructor create a "NULL" id?

Tags:

c++

linux

gcc

c++11

The following code failed in my gcc version 4.8.0:

#include <thread>
#include <cassert>

int main() {
    std::thread::id nobody;

    assert( nobody != std::this_thread::get_id() );
};

Is this behavior correct?

like image 403
André Puel Avatar asked Apr 17 '13 15:04

André Puel


1 Answers

UPDATE: Jonathan Wakely kindly looked at the issue an he says (below in comments) that -pthread has to be passed to both the compiler and the linker. If I do that the code does not fail with gcc 4.7.2 either. So the answer has apparently nothing to do with the quoted e-mail. Thanks Jonathan!


Here are some quotes straight form the gcc developer Jonathan Wakely's mail, written in 2011:

All the comparison operators on our std::thread::id rely on undefined behaviour because our thread::id is just a pthread_t.

[...]

2) operator== uses pthread_equal, which is undefined for invalid thread IDs, POSIX says:

   If either t1 or t2 are not valid thread IDs, the behavior is undefined.
Although it was written two years ago, it probably still applies. At the moment I cannot check the gcc codebase to say more.

Weird. The following code:

#include <iostream>
#include <thread>

int main() {

    std::cout << "Started" << std::endl;

    std::thread::id nobody;

    if ( nobody != std::this_thread::get_id() )  {

      std::cout << "OK" << std::endl;
    }

    std::cout << "Finished" << std::endl;
}

produces:

Started 
OK 
Finished

Check here. However your code does fail with 4.7.2.

like image 142
Ali Avatar answered Nov 14 '22 22:11

Ali