c - 为什么使用线程时程序的输出总是不同?

标签 c multithreading pthreads

我的程序所需的功能:
使用命令行用户输入NMN 是将要创建的新线程的数量,M 是每个线程递增全局变量 A 的数量。

这是我的代码:

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

static int A = 0;

void *Thread(void* x){
        int i;
        int n = *((int*)x);
        for (i = 0; i<n; i++){
                A++;
        }
}

int main(int argc, char* argv[]){
        int i;
        int N = atoi(argv[1]);
        int M = atoi(argv[2]);

        pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t)*N);

        if(!thread){
                printf("No memory\n");
                exit(2);
        }

        for (i = 0; i< N; i++){
                if (pthread_create(&thread[i], NULL, Thread, &M)){
                        printf("Not able to create a thread\n");
                        exit(1);
                }
        }

        for(i = 0; i< N; i++)
                pthread_join(thread[i], NULL);

        printf("A = %d\n", A);

        return 0;
}

问题是每次我运行它时都会有不同的输出。 Screenshot of my terminal when i run the program multiple times in a row

最佳答案

问题是您正在创建多个线程,这些线程并行地尝试同时修改静态 A 全局变量,而没有任何类型的保护。

这意味着根据线程的调度,全局变量的更改不会是原子的,从而产生这种效果。

您可以使用互斥锁来解决此问题,并声明它:

pthread_mutex_t mutex;

并使用 pthread_mutex_init 和 pthread_mutex_destroy 初始化/释放它。

在线程内部,在进行更改之前,使用 pthread_mutex_lock 保护要更改的资源,并使用 pthread_mutex_unlock 释放它。所以代码会改成这样:

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

static int A = 0;
pthread_mutex_t mutex;


void *Thread(void* x){
        int i;
        int n = *((int*)x);

        pthread_mutex_lock(&mutex);
        A += n;
        pthread_mutex_unlock(&mutex);
}

int main(int argc, char* argv[]){
        int i;
        int N = atoi(argv[1]);
        int M = atoi(argv[2]);

        pthread_mutex_init(&mutex, NULL);
        pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t)*N);

        if(!thread){
                printf("No memory\n");
                exit(2);
        }

        for (i = 0; i< N; i++){
                if (pthread_create(&thread[i], NULL, Thread, &M)){
                        printf("Not able to create a thread\n");
                        exit(1);
                }
        }

        for(i = 0; i< N; i++)
                pthread_join(thread[i], NULL);

        printf("A = %d\n", A);

        pthread_mutex_destroy(&mutex);

        return 0;
}

关于c - 为什么使用线程时程序的输出总是不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40564788/

相关文章:

c - 什么是在 RTOS 中将参数传递给堆栈?

c - C中结构对象的内存位置

java - OCJP 转储线程同步方法

multithreading - Delphi 10 : Correct way to run tasks simultaneously

c - 在 for 循环中一遍又一遍地创建和连接线程 (C)

计算文件中字符数、单词数和行数的C代码

c - 函数返回表

c - 在 OpenMP 中,线程如何使用具有全局范围的变量的不同值?

c - 如何在 pthread 中使用 C popen

在 C 中创建线程