【问题标题】:C++ gettid() was not declared in this scopeC++ gettid() 未在此范围内声明
【发布时间】:2015-08-21 05:33:33
【问题描述】:

一个简单的程序是: 我想使用这个 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();
}

编译时出错; gettid()的使用已经按照man page做了:

$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();

【问题讨论】:

    标签: c++11 linux-kernel system-calls boost-thread


    【解决方案1】:

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

    #include <unistd.h>
    #include <sys/syscall.h>
    #define gettid() syscall(SYS_gettid)
    

    【讨论】:

    【解决方案2】:

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

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

    注意事项

    Glibc 没有为这个系统调用提供封装;使用 syscall(2) 调用它。

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

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

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

    【讨论】:

    • “没有 glibc 包装器”并没有“明确说明”。
    • 已在 glibc 2.30 中修复
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 1970-01-01
      • 2021-07-17
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多