Home > Enterprise >  Why MultiThread is slower than Single?? (Linux,C,using pthread)
Why MultiThread is slower than Single?? (Linux,C,using pthread)

Time:05-23

I have a question with MultiThread. This code is simple Example about comparing Single Thread vs MultiThread. (sum 0~400,000,000 with singlethread vs 4-multiThread)

//Single
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>

#define NUM_THREAD 4
#define MY_NUM 100000000

void* calcThread(void* param);
double total = 0;
double sum[NUM_THREAD] = { 0, };
int main() {
    long p[NUM_THREAD] = {MY_NUM, MY_NUM * 2,MY_NUM * 3,MY_NUM * 4 };
    int i;
    long total_nstime;
    struct timespec begin, end;
    pthread_t tid[NUM_THREAD];
    pthread_attr_t attr[NUM_THREAD];
    clock_gettime(CLOCK_MONOTONIC, &begin);
    for (i = 0; i < NUM_THREAD; i  ) {
        calcThread((void*)p[i]);
    }
    for (i = 0; i < NUM_THREAD; i  ) {
        total  = sum[i];
    }
    clock_gettime(CLOCK_MONOTONIC, &end);
    printf("total = %lf\n", total);
    total_nstime = (end.tv_sec - begin.tv_sec) * 1000000000   (end.tv_nsec -    begin.tv_nsec);
    printf("%.3fs\n", (float)total_nstime / 1000000000);
    return 0;
}
void* calcThread(void* param) {
    int i;
    long to = (long)(param);
    int from = to - MY_NUM   1;
    int th_num = from / MY_NUM;
    for (i = from; i <= to; i  )
        sum[th_num]  = i;
    }

I wanna change using 4-MultiThread Code, so I changed that calculate function to using MultiThread.

...
int main() {
    ...
    //createThread
    for (i = 0; i < NUM_THREAD; i  ) {
        pthread_attr_init(&attr[i]);
        pthread_create(&tid[i],&attr[i],calcThread,(void *)p[i]);
    }
    //wait
    for(i=0;i<NUM_THREAD;i  ){
        pthread_join(tid[i],NULL);
    }
    for (i = 0; i < NUM_THREAD; i  ) {
        total  = sum[i];
    }   
    clock_gettime(CLOCK_MONOTONIC, &end);
    ...
}

Result(in Ubuntu) But,It's slower than Single Function Code. I know MultiThread is faster. I have no idea with this problem :( What's wrong? Could you give me some advice ? Thanks a lot!

CodePudding user response:

"I know MultiThread is faster"

This isn't always the case, as generally you would be CPU bound in some way, whether that be due to core count, how it is scheduled at the OS level, and hardware level.

It is a balance how many threads is worth giving to a process, as you may run into an old Linux problem where you would be spending more time scheduling the processes than actually running them.

As this is very hardware and OS dependant, it is difficult to say exactly what the issue may be, but make sure you have the appropriate microcode for your CPU installed (generally installed by default in Ubuntu), but just in case, try:

sudo apt-get install intel-microcode 

Otherwise look at what other processes are being run, and it may be that a lot of other things are running on the cores that are being allocated the process.

  • Related