C++ gettid()未在此范围内声明

Hie*_*erg 12 system-calls boost-thread linux-kernel c++11

一个简单的程序是:我想使用这个gettid函数获取两个线程的线程ID.我不想直接做sysCall.我想使用这个功能.

#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();
}
Run Code Online (Sandbox Code Playgroud)

它在编译时给出错误; gettid()的使用已根据手册页完成:

$g++ -std=c++11 -o Intrpt Interrupt.cpp -lboost_system -lboost_thread
Interrupt.cpp: In function ‘void func()’:
Interrupt.cpp:17:25: error: ‘gettid’ was not declared in this scope
      pid_t tid = gettid();
Run Code Online (Sandbox Code Playgroud)

Gle*_*ard 26

这是一个愚蠢的glibc错误.像这样解决它:

#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
Run Code Online (Sandbox Code Playgroud)

  • 那不是错误,手册页指出,请参见答案/sf/answers/2147704891/ (2认同)
  • 已在 glibc 2.30 中修复 (2认同)

Tho*_*ski 6

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

#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 30
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
#endif
Run Code Online (Sandbox Code Playgroud)


小智 5

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

注意:此系统调用没有glibc包装器。请参阅注释。

笔记

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

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

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

但是您可能还是不应该。您可以改为使用pthread_self()(并使用进行比较pthread_equal(t1, t2))。也可能boost::thread有其自己的等效项。

  • 说“没有glibc包装器”并没有“明确说明”。 (5认同)