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;
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值