一般有四种
参考链接:Linux下获取线程ID
#include <pthread.h>
#include <thread>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)
#define NUM_THREADS 5
using namespace std;
// 线程的运行函数
mutex mtx;
void fun(){
std::unique_lock<std::mutex> lck(mtx);
cout<<"This in fun()"<<endl;
cout<<"process id: "<<getpid()<<endl;
cout<<"kernel id: "<<gettid()<<endl;
cout<<"std thread id: "<< std::this_thread::get_id()<<endl;
cout<<"pthread id:"<< pthread_self()<<endl;
}
void* say_hello(void* args)
{
cout<<"process id: "<<getpid()<<endl;
cout<<"kernel id: "<<gettid()<<endl;
cout<<"std thread id: "<< std::this_thread::get_id()<<endl;
cout<<"pthread id:"<< pthread_self()<<endl;
fun();
return 0;
}
int main() {
//int t =
// 定义线程的 id 变量,多个变量使用数组;
cout<<"process id: "<<getpid()<<endl; // 获取的是进程识别码,不唯一
cout<<"kernel id: "<<gettid()<<endl; // 从内核获取线程id,唯一,使用前需要进行封装
cout<<"std thread id: "<< std::this_thread::get_id()<<endl; // thread类封装得到的id,每个线程唯一
cout<<"pthread id:"<< pthread_self()<<endl; // 同thread类
pthread_t tids[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; ++i)
{
//参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
if (ret != 0)
{
cout << "pthread_create error: error_code=" << ret << endl;
}
}
//等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
pthread_exit(NULL);
return 0;
}
版权声明:本文为qq_44700810原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。