c++获取线程id,编译出错:test.cpp:16:20: 错误:‘gettid’在此作用域中尚未声明

为了测试获取线程id,所以用

#include <unistd.h>
pid_t tid = gettid();
 cout << "now pid is:" << tid << endl; 

但是每次编译都会报错:

[root@localhost cpp]# g++ test.cpp -o test  -lpthread
test.cpp: 在函数‘void* say_hello(void*)’中:
test.cpp:16:20: 错误:‘gettid’在此作用域中尚未声明
 pid_t tid = gettid();
解决办法:

加入以下,

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

贴完整测试代码:

#include <iostream>

#include <ctime>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
using namespace std;

#define NUM_THREADS 5


void* say_hello(void* args)
{
        cout << "Hello Runoob!" << endl;

pid_t tid = gettid();
        cout << "now pid is:" << tid << endl;
return 0;
}
int main()
{
 

        pthread_t tids[NUM_THREADS];
        for (int i = 0; i < NUM_THREADS; ++i)
        {

                int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
                if (ret != 0)
                {
                        cout << "pthread_create error: error_code=" << ret << endl;

                }
else
                {
                        cout << "tids:" << tids[i] << endl;
                }
        }

        pthread_exit(NULL);
        cin.get();
        return 0;
}
 

猜你喜欢

转载自blog.csdn.net/yuhan61659/article/details/81294278