threads have the same id

两盒软妹~` 提交于 2020-01-05 08:09:28

问题


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)

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;
}

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

I wonder, are new threads really created?

Thanks in advance!


回答1:


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.



来源:https://stackoverflow.com/questions/15723498/threads-have-the-same-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!