pthreads - 读取和写入全局变量

时间:2017-10-31 11:35:35

标签: pthreads

我正在学习pthreads并且我创建了一个程序,它创建了10个线程,其中5个读取全局变量的值,5个更新全局变量的值。以下是该程序的一些示例输出。

我的问题是为什么在write()线程中它总是说共享变量是2,即使每次创建write()线程时它都在更新?我希望它能改变。

输出:

Write thread - shared variable was 2 and it is now 22
Read Thread - The shared variable is 2
Write thread - shared variable was 2 and it is now 9
Write thread - shared variable was 2 and it is now 12
Write thread - shared variable was 2 and it is now 37
Write thread - shared variable was 2 and it is now 43
Read Thread - The shared variable is 2
Read Thread - The shared variable is 43
Read Thread - The shared variable is 43
Read Thread - The shared variable is 43

代码:

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


#define NUM_THREADS 5
int shared_varibale = 2;

void *read(void *param);
void *write(void *param);

int main (int argc, char *argv[]) {


    int i;
    time_t t;
    pthread_t tid[NUM_THREADS];

    /* Intializes random number generator */
    srand((unsigned) time(&t));

    /*Create 5 write threads*/
        for(i = 0; i < NUM_THREADS; i++) {
            pthread_create(&tid[i], NULL, write, &shared_varibale);
        }

    /*Create 5 read threads*/
    for(i = 0; i < NUM_THREADS; i++) {
        pthread_create(&tid[i], NULL, read, &shared_varibale);
    }

    return 0;
}

void *read(void *param) {
    int *p = (int*)param;
    printf("The variable is %d\n", *p);
    pthread_exit(NULL);
}


void *write(void *param) {

    int *p = (int*)param;
    int rand_varibale = rand() % 50;
    printf("Write thread - shared variable was %d and it is now %d\n", *p, rand_varibale);
    *p = rand_varibale;
    pthread_exit(NULL);
}

1 个答案:

答案 0 :(得分:1)

首先,您不应该调用自己的函数readwrite,因为POSIX已经使用了这些标识符。您还应该对所有函数调用添加错误检查,因为如果不这样做,很容易错过问题。

您的示例中没有同步,因此您有数据竞争。除此之外,这意味着线程可能会看到过时的值。并且您不会对线程的执行施加任何顺序。如果您的硬件支持那么多的并行性,那么所有线程可能会执行,直到printf调用(导致所有这些线程除了一个阻塞之外)。由于共享变量仅在printf调用之后写入,因此您将获得所见的结果。