线程具有相同的id(threads have the same id)

2019-10-17 22:12发布

我学线程。 我已阅读,线程终止后它是一个功能(即作为参数传递给pthread_create函数)。 所以我创建循环线程,它们是执行事后又被终止。 (对不起,一些长码)

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

 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没有被改变:

我不知道,是新主题的确产生?

提前致谢!

Answer 1:

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



文章来源: threads have the same id
标签: c linux pthreads