简体   繁体   中英

Why does my simple counting program take longer to run with multiple threads? (in C)

Here's my code:

#define COUNT_TO 100000000
#define MAX_CORES 4

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
long long i = 0;

void* start_counting(void *arg){
    for(;;){

        pthread_mutex_lock(&mutex);

        if(i >= COUNT_TO){
            pthread_mutex_unlock(&mutex);
            return NULL;
        }
        i++;
        pthread_mutex_unlock(&mutex);
        //printf("i = %lld\n", i);
    }
}

int main(int argc, char* argv[]){
    int i = 0;

    pthread_t * thread_group = malloc(sizeof(pthread_t) * MAX_CORES);

    for(i = 0; i < MAX_CORES; i++){
        pthread_create(&thread_group[i], NULL, start_counting, NULL);
    }

    for(i = 0; i < MAX_CORES; i++){
        pthread_join(thread_group[i], NULL);
    }

    return 0;
}

This is what your threads do:

  1. Read the value of i .
  2. Increment the value we read.
  3. Write back the incremented value of i .
  4. Go to step 1.

Cleary, another thread cannot read the value of i after a different thread has accomplished step 1 but before it has completed step 3. So there can be no overlap between two threads doing steps 1, 2, or 3.

So all your threads are fighting over access to the same resource -- i (or the mutex that protects it). No thread can make useful forward progress without exclusive access to one or both of those. Given that, there is no benefit to using multiple threads since only one of them can accomplish useful work at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM