我正在编写一个解析 HTML 的程序,但是,当它解析多个 HTML 文件时,我需要对一组 IP 执行 DNS 查找。我正在考虑pthreads用于查找任务。
你会推荐这样做吗?我需要多个线程来完成这项任务吗?我可能会遇到哪些潜在问题?任何反馈表示赞赏。
这就是我在想的...
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void *ip2host(void *ips[][2]){
    struct hostent *hent;
    struct in_addr addr;
    int i;
    for (i=0;i<3;i++) {
        if(!inet_aton(ips[i][0], &addr))
            return NULL;
        if((hent = gethostbyaddr((char *)&(addr.s_addr), sizeof(addr.s_addr), AF_INET))){
            ips[i][1] = malloc (strlen (hent->h_name) + 1);
            strcpy(ips[i][1], hent->h_name);
        }
    }
    return NULL;
}
int main(){
    char *ips[][2] = {
        {"199.21.99.110", NULL},
        {"66.249.73.55", NULL},
        {"74.125.225.34", NULL}
    };
    pthread_t thread1;
    if(pthread_create(&thread1, NULL, ip2host, &ips)) {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }
    // parse html files
    int y = 0;
    while(++y < 100000);
    printf("y increment finished\n");
    if(pthread_join(thread1, NULL)) {
        fprintf(stderr, "Error joining thread\n");
        return 1;
    }
    int i;
    for(i=0; i<3; i++) {
        printf("%s\n", ips[i][1]);
    }
    return 0;
}