如何解决如何获取创建时给出的pthread的id?
在创建 pthread 时,使用 pthread_create()
。这个函数的第一个参数是thread_id。
我试图访问这个值 pthread_self()
但这给出了一些非常大的东西而不是我在创建时给出的数字。
有没有办法访问这个值?
for(int i = 0; i < necessaryThreadCount; i++){
pthread_create(&threadIDs[i],NULL,theFunction,(void*)&requiredstructre[i]);
}
我的问题是,如何访问函数中给定线程 ID 的值?
解决方案:
解决方法
第一个参数是指向需要首先声明的 thread_id 的指针。 使用 pthread_create() 创建线程后,将分配 ID。参考以下:
int main()
{
pthread_t thread; // declare thread
pthread_create(&thread,NULL,func,NULL);
printf("the thread id = %d\n",thread);
}
,
thread_id 用于创建的新线程。如果您在当前线程中执行 pthread_self(),它将返回与新创建线程不同的值。
希望下面的例子可以帮助你理解线程 id 的创建: [注意:声明全局 pthread_t 不是一个好主意] 示例:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_t ctid;
void* thread_function(void* arg)
{
printf("Inside the thread\n");
printf("ctid: %ld,self: %ld",ctid,pthread_self());
// exit the current thread
pthread_exit(NULL);
}
void createthread()
{
pthread_create(&ctid,&thread_function,NULL);
printf("This line may be printed"
" before thread terminates\n");
// Waiting for the created thread to terminate
pthread_join(ctid,NULL);
pthread_exit(NULL);
}
// Driver code
int main()
{
createthread();
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。