Linux线程ID比较

所以,我在结构列表中find一个当前的线程ID非常糟糕,它反映了关于线程的信息。

基本上,列表中的每个元素都有一个字段pthread_t id 。 我的searchfunction是这样的:

 int thread_pos(pthread_t tid) { int i; for (i = 0; i < my_threads.thread_num; i++) { printf("for: %d %d %d\n", my_threads.vector[i].id, tid, pthread_equal(my_threads.vector[i].id, tid)); if (pthread_equal(my_threads.vector[i].id, tid)) { printf("found\n"); return i; } } return -1; } 

由于my_threads.vector中只有一个元素,所以会打印一行:

 419817216 419817216 0 

数据结构:

 struct my_thread_t { pthread_t id; }; struct my_threads_t { struct my_thread_t vector[100]; int thread_num; }; 

我添加元素以这种方式列出:

 pthread_create(&new_tid, NULL, start_thread, &my_threads.vector[my_threads.thread_num].thread_arg); my_threads.vector[my_threads.thread_num].id = new_tid; my_threads.thread_num++; 

问题是,虽然元素在列表中,但是却无法find它。 我在每个比较上打印了一行(例如419817216 419817216 0 ,显示列表中的tid,键tid和pthread_equal的结果)。 正如你所看到的,数字表示是相同的,但不知何故,pthread_equal表示他们不是。

我错过了什么?

如果你从不同线程向my_threads添加/删除/检查元素,一切都可能变得疯狂。 从你的代码片段我猜你没有这个结构的互斥保护。

如果你真的没有实现锁定,并且需要更多的时候读取列表,请考虑一下pthread_rwlock()接口。

更新:你也可以在你的平台上检查sizeof(pthread_t)吗? 如果是8(无符号长整型),至少应该in printf中使用%lu格式。