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

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


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).