thread_t 数组 linux,首页 C#如何打印pthread_t
好的,這似乎是我的最終答案。 我們有2個(gè)實(shí)際問(wèn)題:
如何獲取較短的唯一ID以供線程記錄。
無(wú)論如何,我們需要為線程打印真實(shí)的pthread_t ID(至少鏈接到POSIX值)。
1.打印POSIX ID(pthread_t)
您可以簡(jiǎn)單地將pthread_t視為字節(jié)數(shù)組,并為每個(gè)字節(jié)打印十六進(jìn)制數(shù)字。 因此,您不受某些固定大小類型的限制。 唯一的問(wèn)題是字節(jié)順序。 您可能喜歡打印字節(jié)的順序與簡(jiǎn)單的“ int”打印順序相同。 這是little-endian的示例,并且big-endian僅應(yīng)還原順序(在define?下):
#include
#include
void print_thread_id(pthread_t id)
{
size_t i;
for (i = sizeof(i); i; --i)
printf("%02x", *(((unsigned char*) &id) + i - 1));
}
int main()
{
pthread_t id = pthread_self();
printf("%08x\n", id);
print_thread_id(id);
return 0;
}
2.獲得較短的可打印線程ID
在任何建議的情況下,您都應(yīng)將實(shí)際線程ID(posix)轉(zhuǎn)換為某些表的索引。 但是有兩種明顯不同的方法:
2.1。 跟蹤線程。
您可以跟蹤表中所有現(xiàn)有線程的線程ID(應(yīng)該包裝它們的pthread_create()調(diào)用),并具有“重載”的id函數(shù),該函數(shù)僅使您獲得表索引,而不是實(shí)際的線程ID。 此方案對(duì)于任何內(nèi)部線程相關(guān)的調(diào)試資源跟蹤也非常有用。 明顯的優(yōu)勢(shì)是線程級(jí)跟蹤/調(diào)試功能的副作用,并可能在將來(lái)進(jìn)行擴(kuò)展。 缺點(diǎn)是必須跟蹤任何線程的創(chuàng)建/銷毀。
這是部分偽代碼示例:
pthread_create_wrapper(...)
{
id = pthread_create(...)
add_thread(id);
}
pthread_destruction_wrapper()
{
/* Main problem is it should be called.
pthread_cleanup_*() calls are possible solution. */
remove_thread(pthread_self());
}
unsigned thread_id(pthread_t known_pthread_id)
{
return seatch_thread_index(known_pthread_id);
}
/* user code */
printf("04x", thread_id(pthread_self()));
2.2。 只需注冊(cè)新的線程ID。
在記錄期間調(diào)用pthread_self()并搜索內(nèi)部表(如果它知道線程)。如果創(chuàng)建了具有此類ID的線程,則使用其索引(或從以前的線程重復(fù)使用,實(shí)際上沒(méi)關(guān)系,因?yàn)橥粫r(shí)間沒(méi)有2個(gè)相同的ID)。 如果線程ID未知,則創(chuàng)建新條目,以便生成/使用新索引。
優(yōu)點(diǎn)是簡(jiǎn)單。 缺點(diǎn)是無(wú)法跟蹤線程的創(chuàng)建/銷毀。 因此,要跟蹤此情況,需要一些外部機(jī)制。
總結(jié)
以上是生活随笔為你收集整理的thread_t 数组 linux,首页 C#如何打印pthread_t的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 手机控制linux电脑,通过Amora用
- 下一篇: linux 设计一个程序,要求打开文件