for循环中的线程

Joh*_*ohn 1 c for-loop pthreads

我正在用C编写一个程序来计算某些网站的访问时间.网站名称存储在urls数组的每个元素中.如果我取出for(y = 0; y <iterations; y ++)循环,那么一切运行正常.但是,如果我保留它.urls [0],第一个网站,在第二个for循环完全完成并增加y之后搞砸了

是什么导致了这个?

char *urls[50]; char str1[20];

void *wget(void *argument)
{
  int threadid;
  threadid = *((int *)argument);
  strcpy(str1, "wget -q --spider ");
  strcat(str1, urls[threadid]);
  system(str1);
}


for (y = 0; y < iterations; y++)
{
  for (j = 0; j < numthreads; j++)
  {
        thread_args[j] = j;

        clock_gettime(CLOCK_REALTIME, &bgn);
        rc = pthread_create(&threads[j], NULL, wget, (void *) &thread_args[j]);
        rc = pthread_join(threads[j], NULL);
        clock_gettime(CLOCK_REALTIME, &nd);
        times[j] = timediff(bgn,nd);
  }
}
Run Code Online (Sandbox Code Playgroud)

Qua*_*nic 5

一些可能性......

str1似乎在所有线程中共享.那就是麻烦的秘诀.

str1只有20个字符长.很难相信wget包括URL在内的整个命令行将少于20个字符.所以你要写完了str1.

考虑创建str1一个局部变量wget(),并使其成为一个足够大的char数组,以处理wget您可能拥有的最大可能命令行,或者动态分配它并wget()使用基于命令行常量部分长度的大小释放它和当前的URL.