gpt4 book ai didi

c++ - 如何打印 pthread_t

转载 作者:IT老高 更新时间:2023-10-28 12:35:15 27 4
gpt4 key购买 nike

已搜索,但没有找到令人满意的答案。

我知道没有可移植的方式来打印 pthread_t。

你是如何在你的应用中做到这一点的?

更新:

实际上我不需要 pthread_t,而是一些小的数字 id,在调试消息中标识不同的线程。

在我的系统(64 位 RHEL 5.3)上,它被定义为 unsigned long int,所以它是一个很大的数字,打印它会在调试行中占据一个有值(value)的位置。 gdb 如何分配短时间?

最佳答案

这将打印出 pthread_t 的十六进制表示。 ,不管那实际上是什么:

void fprintPt(FILE *f, pthread_t pt) {
unsigned char *ptc = (unsigned char*)(void*)(&pt);
fprintf(f, "0x");
for (size_t i=0; i<sizeof(pt); i++) {
fprintf(f, "%02x", (unsigned)(ptc[i]));
}
}

为每个 pthread_t 打印一个小 id可以使用类似的东西(这次使用 iostreams):

void printPt(std::ostream &strm, pthread_t pt) {
static int nextindex = 0;
static std::map<pthread_t, int> ids;
if (ids.find(pt) == ids.end()) {
ids[pt] = nextindex++;
}
strm << ids[pt];
}

取决于平台和 pthread_t 的实际表示这里可能需要定义一个 operator<对于 pthread_t , 因为 std::map需要对元素进行排序:

bool operator<(const pthread_t &left, const pthread_t &right) {
...
}

关于c++ - 如何打印 pthread_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1759794/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com