c - 使用 pthreads 计算多个网页中 anchor 标记的数量

标签 c multithreading parsing pthreads

我目前正在做一个涉及线程的作业,而且我不是专业程序员,所以我正在学习如何使用线程。我的任务是计算网页中 anchor 标记的数量,我得到了一个包含 100 个 url 的 txt 文件,我减少到 5 个 url,以便我可以对其进行测试,目标是返回每个 URL 上找到的 anchor 标记的数量。

我的问题是,当我在没有 for 循环的情况下运行代码时,它工作正常,但使用 for 循环时,它不会调用线程中的函数。

我想要做的是使用 for 循环,因为我将循环 100 个 URL。

void runThreads(int num_urls){

pthread_t threads[100];

for ( x=0; x<num_urls-1; x++ ) 
{

     pthread_create(&threads[x], NULL,(void *) th_run,(void *) &x);

}

使用 for 循环时出现错误的输出...只有最后一个线程真正起作用。 th_run 接受一个 int* i ,EXP: void th_run( int* i )。我怎样才能解决这个竞争条件?

URL=www.google.com
CNT=0
FD=-1
URL=www.facebook.com
CNT=0
FD=-1
URL=www.youtube.com
CNT=9
FD=3

最佳答案

所有线程都获得相同的参数,&t。当第一个线程有机会运行时,循环已完成,它指向的值,即 t 的值,是 num_urls,所以确实所有线程使用相同的参数运行。

编辑:最直接的修复方法是不传递索引(线程实际上并不关心),而是传递线程应处理的数据地址:

    pthread_create(&threads[t], NULL,(void *) th_run, &web_array[t]);

它看起来也像是越界访问。通常,web_array[num_urls] 应该无效,但如果没有看到 read_url_file 代码,很难确定(它有 while (!feof()) 循环,不是吗?)。

关于c - 使用 pthreads 计算多个网页中 anchor 标记的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40047064/

相关文章:

c - SunOS 上的 stderr 上没有消息的 "system()"如何处理

Java 线程亲和性

arrays - 将 XML 数据存储为数组,Swift

C 在数组中添加和搜索已解析的数据

c - Speller - 卸载特里树 - 功能无法正常工作

c - 将结构数组传递给函数

multithreading - 什么样的应用程序需要多线程?

parsing - lexer是否可以将错误 token 传递给解析器?

c - 将 windows.h 与 main() 一起使用

c - Linux 套接字终止监听线程