for 循环中的线程
我正在用 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);
}
}
I'm writing a program in C to calculate the access time to certain websites. The sitenames are stored in each element of urls array. If I take out the for (y = 0; y < iterations; y++) loop, then everything runs fine. But if if I keep it. urls[0], the first website, gets messed up after the second for loop completely finishes and increments y
What's causing this?
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一些可能性...
str1
似乎在所有线程之间共享。这就是麻烦的根源。str1
只有 20 个字符长。很难相信整个wget
命令行(包括 URL)将少于 20 个字符。因此,您正在注销str1
的末尾。考虑将
str1
设为wget()
中的局部变量,或者将其设为足够大的 char 数组,以处理您可能遇到的最大的wget
命令行可能有,或者动态分配它并在wget()
中释放它,其大小基于命令行常量部分的长度和当前 URL。Some possibilities...
str1
appears to be shared among all the threads. That's a recipe for trouble right there.str1
is only 20 chars long. Hard to believe the wholewget
command line including the URL will be less than 20 chars. So you're writing off the end ofstr1
.Consider making
str1
a local variable inwget()
, and either make it a char array big enough to handle the largest possiblewget
command line you might have, or dynamically allocate it and free it withinwget()
with a size based on the length of the constant part of the command line and the current URL.我敢打赌,
urls
中的字符串之一 + wget 字符串的长度超过 20 个字节,并且会覆盖该数据。使str1
更大,并将其移至 wget 函数中(多个线程不应在没有锁定的情况下写入一个共享资源)。My bet is that one of the strings in
urls
+ the wget string are longer than 20 bytes and are overwriting that data. Makestr1
larger, and move it into your wget function (multiple threads should not be writing to one shared resource without locking).