微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何获取创建时给出的pthread的id?

如何解决如何获取创建时给出的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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?