简体   繁体   English

为什么我的简单计数程序需要更长的时间才能运行多个线程? (在 C 中)

[英]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 .读取i的值。
  2. Increment the value we read.增加我们读取的值。
  3. Write back the incremented value of i .写回i的增量值。
  4. Go to step 1. Go 到步骤 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.显然,在另一个线程完成步骤 1 之后但在完成步骤 3 之前,另一个线程无法读取i的值。因此,执行步骤 1、2 或 3 的两个线程之间不能有重叠。

So all your threads are fighting over access to the same resource -- i (or the mutex that protects it).所以你所有的线程都在争夺对同一个资源的访问i (或保护它的互斥锁)。 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.鉴于此,使用多个线程没有任何好处,因为一次只有一个线程可以完成有用的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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