What costs the extra execution time of the routine in a pthread program?

烈酒焚心 提交于 2019-12-05 05:58:20

It's probably because creation of any thread forces libc to use synchronization in getc. This makes this function significantly slower. Following example is for me as slow as version 3:

void *skip(void *p){ return NULL; };
pthread_create(&new_thread, NULL, skip, NULL);
count_words(&file1); 
count_words(&file2); 

To fix this problem you can use a buffer:

for (i = 0; i < N; i++) {
    char buffer[BUFSIZ];
    int read;
    do {
        read = fread(buffer, 1, BUFSIZ, fp);
        int j;
        for(j = 0; j < read; j++) {
            if (!isalnum(buffer[j]) && isalnum(prevc))
                file->words++;
            prevc = buffer[j];
        }
    } while(read == BUFSIZ);
    fseek(fp, 0, SEEK_SET);
}

In this solution, IO functions are called rarely enough to make synchronization overhead insignificant. This not only solves problem of weird timings, but also makes it several times faster. For me it's reduction from 0.54s (without threads) or 0.85s (with threads) to 0.15s (in both cases).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!