并发性:使用pthread_mutex原子化增量操作

时间:2018-10-22 16:23:34

标签: c concurrency pthreads mutex

我目前正在阅读操作系统:三篇简单文章,并且我开始了解并发背后的逻辑。在第26章中,我们得到了线程和原子性问题的示例:

#include <stdio.h>
#include <pthread.h>
#include <assert.h>

static volatile int counter = 0;

// mythread()
// Simply adds 1 to counter repeatedly, in a loop
// No, this is not how you would add 10,000,000 to
// a counter, but it shows the problem nicely.

void *mythread(void *arg){
    printf("%s: begin\n", (char *) arg);
    int i;
    for (i = 0; i < 1e7; i++) {
        counter = counter + 1;
    }
    printf("%s: done\n", (char *) arg);
    return NULL;
}


// main()
// Just launches two threads (pthread_create)
// and then waits for them (pthread_join)

int main(int argc, char *argv[]) {
    pthread_t p1, p2;
    printf("main: begin (counter = %d)\n", counter);
    pthread_create(&p1, NULL, mythread, "A");
    pthread_create(&p2, NULL, mythread, "B");

    // join waits for the threads to finish
    pthread_join(p1, NULL);
    pthread_join(p2, NULL);
    printf("main: done with both (counter = %d)\n", counter);
    return 0;

}

它向我们展示了一个问题,就是由于种族条件的增加,总和的值会发生变化,而很少是假定的。

每个示例,编译后:

gcc -g -o main page6.c -Wall -pthread

运行两次,我得到:

main: begin (counter = 0)
A: begin
B: begin
A: done
B: done
main: done with both (counter = 10263001)

和:

main: begin (counter = 0)
A: begin
B: begin
A: done
B: done
main: done with both (counter = 10600399)

因此,在阅读了有关互斥的内容之后,我尝试对mythread()函数中的代码进行了少许更改。

void *mythread(void *arg){
    pthread_mutex_t lock;
    int rc = pthread_mutex_init(&lock,NULL);
    assert(rc==0); //always check sucess

    printf("%s: begin\n", (char *) arg);
    int i;

    for (i = 0; i < 1e7; i++) {
        pthread_mutex_lock(&lock);
        counter = counter + 1;
        pthread_mutex_unlock(&lock);
    }

    printf("%s: done\n", (char *) arg);
    return NULL;
}

并且以相同的方式编译并运行之后,确实需要花费更多的时间(1-2秒)。

但是结果并没有更好:

main: begin (counter = 0)
A: begin
B: begin
B: done
A: done
main: done with both (counter = 10019830)

和:

main: begin (counter = 0)
A: begin
B: begin
B: done
A: done
main: done with both (counter = 10008806)

那为什么不起作用?这不应该在代码中创建关键部分吗?我缺少明显的东西吗?

1 个答案:

答案 0 :(得分:3)

您不应该在mythread中将互斥锁作为局部变量使用,因为每个线程随后都会得到它自己的副本。使其全局并在main中对其进行初始化。