在C中接收相同ID的线程

时间:2012-10-25 00:25:01

标签: c multithreading for-loop

这是一个代码块,用于创建用户提供的多个线程,然后每个线程生成一个随机数并计算其平方根。我无法弄清楚为什么线程获得相同的ID,第64行是罪魁祸首,因为它是创建线程的地方。我怀疑循环中发生的事情导致所有线程同时生成。

////////////////////////////////////////////////
//
//
// Zach
//
// 
//
//
////////////////////////////////////////////////



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>





void *squareroot(void *num1)
{
  int *id = (int *)num1;
  int incoming = rand()/100;
  float *outgoing = (float *)malloc(sizeof(float));
  printf("%d \n", *id);
  printf("%d\n", incoming);
  *outgoing = 5.000;
  //Calculate the square root of the number passed to the function
  *outgoing = sqrt(incoming);
  return outgoing;

}


int main(int argc, char* argv[])//testing funcion
{
  srand(time(NULL));
  int i, j;
  int *temp = (int *)malloc(sizeof(int));
  if (argc != 2) 
  {

    printf ("ERROR: Enter a number\n");
    return 1;

  }

  int loop = atoi(argv[1]); //grabbing the integer supplied by user
  pthread_t thread_id[loop];
  void *exit_status;
  float *thread_result;

  for(i = 0; i < loop; i++)
  {

    pthread_create(&thread_id[i], NULL, squareroot, &i);
  }


  for(j = 0; j < loop; j++)
  {
    pthread_join(thread_id[j], &exit_status);
    thread_result = (float *)exit_status;
    printf("%f\n", *thread_result);

  }


}

1 个答案:

答案 0 :(得分:2)

我认为正在发生的事情是你的循环在任何线程实际运行之前完成所有线程(或至少其中一些)的创建并提取它们的唯一ID。

因为你传递了一个指向i的指针,当每个线程最终都要检查它的参数时,i已经完成......或者至少在中途完成。危险在于多个线程可能会看到i的相同值。更糟糕的是,你永远不会从该指针复制值 - 你总是取消引用它。这意味着它可能会在线程执行过程中发生变化。

你应该做的是假装它是一个指针:

pthread_create(&thread_id[i], NULL, squareroot, (void*)i);

在你的线程函数中:

int id = (int)num1;

这是有效的,因为指针是按值传递的。无论您提供什么值,都是线程函数的值。以前它没有用,因为你传递了一个指向一个可能在另一个线程中改变的值的指针。

PS:最后不要忘记free循环中每个线程的结果。目前你还没有清理你分配的内存。

相关问题