线程具有相同的id [英] threads have the same id

查看:171
本文介绍了线程具有相同的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习线程。我已阅读,线程终止后,它跳出函数(即作为参数传递给pthread_create的功能)。
所以我创建循环线程,它们被执行,之后他们被终止。
     (抱歉有些长code)

I learn threads. I have read that thread terminates after it is out of a function (that is passed as parameter to pthread_create function). So I create threads in the loop, they are executed and afterwards they are terminated. (sorry for some long code)

但是,当我调用一个函数pthread_create的,新主题得到相同的ID。为什么?

But when I call a function pthread_create, new threads get the same ids. Why?

 struct data {
   FILE *f;
 };

void *read_line_of_file(void *gdata) {
  pthread_mutex_lock(&g_count_mutex); // only one thread can work with file, 
                                   //doing so we block other threads from accessing it
  data *ldata = (data *) gdata;
  char line[80];
  int ret_val  =fscanf(ldata->f,"%s",line);

  pthread_mutex_unlock(&g_count_mutex); // allow other threads to access it

  if (ret_val != EOF)
    printf("%s   %lu\n  ", line, pthread_self());

 // some time consuming operations, while they are being executed by one thread,
 // other  threads are not influenced by it (if there are executed on different cores)
  volatile int a=8;
  for (int i=0;i <10000;i++ )
  for (int i=0;i <10000;i++ ) {
     a=a/7+i;
  }

  if (ret_val == EOF)     // here thread ends
     pthread_exit((void *)1);
   pthread_exit((void *)0);
 }


int main() {
  int kNumber_of_threads=3, val=0;

  pthread_t threads[kNumber_of_threads];
  int ret_val_from_thread=0;

  data  mydata;

  mydata.f = fopen("data.txt","r");
  if ( mydata.f == NULL) {
    printf("file is not found\n");
    return 0;
  }

  for( ; val != 1 ;) {

    // THIS IS THAT PLACE, IDs are the same (according to the number of processes),
    // I expected them to be changing..
    for(int i=0; i<kNumber_of_threads; i++) {
      pthread_create(&threads[i],NULL,read_line_of_file, &mydata);
    }

    for(int i=0; i<kNumber_of_threads; i++) {
      pthread_join(threads[i], (void **) &ret_val_from_thread);
      if (ret_val_from_thread != 0)
        val = ret_val_from_thread;
    }

    printf(" next  %d\n",val);
  }
  printf("work is finished\n");

  fclose(mydata.f);
  return 0;
}

作为结果,我看到线程该ID没有被更改:

as result, I see that id of threads are not being changed:

我不知道,真的是创造了新的主题?

I wonder, are new threads really created?

在此先感谢!

推荐答案

主题的ID只保证是当前正在运行的线程之间的不同。如果你摧毁一个线程,并创建一个新的,它很可能是一个previously使用线程ID创建的。

Thread IDs are only guaranteed to be different among currently running threads. If you destroy a thread and create a new one, it may well be created with a previously used thread ID.

这篇关于线程具有相同的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆