#获取线程ID的方法
获取线程ID的方法
Linux
phread_create
调用pthread_create函数时,第一个参数在函数调用成功后可以得到线程ID:
#include <pthread.h>
// 线程ID
pthread_t id;
pthread_create(&id,NULL,thread_fun,NULL);
此方法获取的ID是一块内存地址,不是全系统唯一的,一般是一个很大的数字(内存地址)。
pthread_self
在需要获取ID的线程中,调用pthread_self()函数获取线程:
#include <pthread.h>
// 线程ID
pthread_t id = pthread_self();
此方法同pthread_create相同。
syscall
使用系统函数获取线程ID:
#include <sys/syscall.h>
#include <unistd.h>
// 线程ID
int id = syscall(SYS_gettid);
此方法获取的线程ID是系统范围内全局唯一的,一般是一个不会太大的整数。
具体区别:
#include <sys/syscall.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
void *thread_fun(void* arg)
{
pthread_t *id1 = (pthread_t*)arg;
pthread_t id2 = pthread_self();
int id3 = syscall(SYS_gettid);
printf("id1:%ld,id2:%ld,id3:%ld\n",id1,id2,id3);
while(true)
{
sleep(1);
}
}
int main()
{
pthread_t id;
pthread_create(&id,NULL,thread_fun,&id);
pthread_join(id,NULL);
return 0;
}
执行结果:id1: 140185007511296, tid2: 140185007511296, tid3: 60837
Windows
_beginthreadex
调用函数_beginthreadex创建线程,最后一个参数返回线程ID:
//线程ID
unsigned int thID;
HANDLE *hth;
hth = (HANDLE)_beginthreadex(NULL, 0, threadFun, NULL, 0, &thID);
GetCurrentThreadID
在需要获取线程代码段中,调用GetCurrentThreadID函数获取当前所在的线程ID:
//线程ID
DWORD id = GetCurrentThreadID();
C++11
std::this_thread::get_id和
使用std::this_thread类的get_id方法获取当前线程ID:
//线程ID
#include <thread>
#include <iostream>
#include <sstream>
void thread_fun();
int main()
{
std::thread thread_(thread_fun);
std::thread::id thread_id = thread_.get_id();
}
std::thread::get_id
使用std::thread类的get_id方法获取指定线程ID:
//线程ID
#include <thread>
#include <iostream>
#include <sstream>
int main()
{
//线程ID
std::thread::id thread_id = std::this_thread::get_id();
}
** 使用get_id方法返回的是一个包装类型的std::thread::id对象,不可以直接强转成整型,也没有提供任何转换整型的接口,因此,一般使用std::cout将id值打印出来。或者先转换为:std::ostringstream对象,再转换成字符串类型,然后再把字符串类型转换成整型.**
//线程ID
#include <thread>
#include <iostream>
#include <sstream>
void worker_thread_func()
{
while (true)
{
}
}
int main()
{
std::thread t(worker_thread_func);
//获取线程 t 的 ID
std::thread::id worker_thread_id = t.get_id();
std::cout << "worker thread id: " << worker_thread_id << std::endl;
//获取主线程的线程 ID
std::thread::id main_thread_id = std::this_thread::get_id();
//先将 std::thread::id 转换成 std::ostringstream 对
std::ostringstream oss;
oss << main_thread_id;
//再将 std::ostringstream 对象转换成 std::string
std::string str = oss.str();
//最后将 std::string 转换成整型值
int threadid = atol(str.c_str());
std::cout << "main thread id: " << threadid << std::endl;
while (true)
{
//权宜之计,让主线程不要提前退出
}
return 0;
}
摘自《C/C++多线程编程精髓》