C++11 C++;此作用域中未声明getId()

C++11 C++;此作用域中未声明getId(),c++11,linux-kernel,system-calls,boost-thread,C++11,Linux Kernel,System Calls,Boost Thread,一个简单的程序是: 我想使用这个getId函数获取两个线程的线程ID。我不想直接进行系统调用。我想使用这个函数 #include <iostream> #include <boost/thread/thread.hpp> #include <boost/date_time/date.hpp> #include <unistd.h> #include <sys/types.h> using namespace boost; using n

一个简单的程序是: 我想使用这个getId函数获取两个线程的线程ID。我不想直接进行系统调用。我想使用这个函数

#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/date_time/date.hpp>
#include <unistd.h>
#include <sys/types.h>
using namespace boost;
using namespace std;

boost::thread thread_obj;
boost::thread thread_obj1;

void func(void)
{
    char x;
    cout << "enter y to interrupt" << endl;
    cin >> x;
     pid_t tid = gettid();
    cout << "tid:" << tid << endl;
    if (x == 'y') {
        cout << "x = 'y'" << endl;    
        cout << "thread interrupt" << endl;
    }
}

void real_main() {

   cout << "real main thread" << endl;
    pid_t tid = gettid();
    cout << "tid:" << tid << endl;

    boost::system_time const timeout = boost::get_system_time() + boost::posix_time::seconds(3);
    try {
        boost::this_thread::sleep(timeout);
    }
    catch (boost::thread_interrupted &) {
        cout << "thread interrupted" << endl;
    }

}

int main()
{
    thread_obj1 = boost::thread(&func);
    thread_obj = boost::thread(&real_main);
    thread_obj.join();
}

您参考的手册页可以在线阅读。它明确指出:

注意:此系统调用没有glibc包装器;见附注

注释

Glibc不提供此系统调用的包装器;使用syscall(2)调用它

此调用返回的线程ID与POSIX线程ID不同(即pthread_self(3)返回的不透明值)

所以你不能。使用此函数的唯一方法是通过syscall


但你可能无论如何都不应该。您可以使用
pthread_self()
(并使用
pthread_equal(t1,t2)
进行比较)。有可能
boost::thread
也有它自己的等价物。

这是一个愚蠢的glibc bug。像这样解决它:

#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
#包括
#包括
#定义gettid()系统调用(SYS\u gettid)

除了Glenn Maynard提供的解决方案之外,检查glibc版本可能是合适的,并且只有当它低于2.30时,才能为getId()定义建议的宏

#如果uuu GLIBC_uuu==2&&uuu GLIBC_uuminor_uuu<30
#包括
#定义gettid()系统调用(SYS\u gettid)
#恩迪夫

关于“没有glibc包装器”的说法没有“明确说明”。在glibc 2.30中已修复。这不是错误,手册页指出,请参阅答案在glibc 2.30中已修复
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 30
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
#endif