C ++ gettid () has not been declared in this area

Simple program: I would like to get the thread id of both threads using this gettid function. I do not want to do sysCall directly. I want to use this feature.

#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(); } 

It gives a compilation error; Using gettid () is done according to the 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(); 
+5
source share
2 answers

This is a stupid glibc error. Work around it like this:

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

The manual page you are linking to can be read online here . It clearly states:

Note. There is no glibc shell for this system call; see NOTES.

and

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall (2).

The thread identifier returned by this call is not the same as the POSIX thread identifier (i.e., the opaque value returned by pthread_self (3)).

So you can’t. The only way to use this function is through syscall.

But you probably shouldn't care. You can use pthread_self() (and compare using pthread_equal(t1, t2) ). It is possible that boost::thread also has its own equivalent.

+2
source

All Articles