gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:52:52 28 4
gpt4 key购买 nike

一个简单的程序是:我想使用 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() 的使用已根据手册页完成:

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

最佳答案

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

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

关于c++11 - C++ gettid() 未在此范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30680550/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com