跳转至
第二部分 · 并发

26.2 为什么更糟糕:共享数据

原书第 201–203 页
整章阅读 ↗

上面演示的简单线程示例非常有用,它展示了线程如何创建,根据调度程序的决定,它们如何以不同顺序运行。但是,它没有展示线程在访问共享数据时如何相互作用。

设想一个简单的例子,其中两个线程希望更新全局共享变量。我们要研究的代码如图26.3所示。

#include <stdio.h>
#include <pthread.h>
#include "mythreads.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;
}

图26.3 共享数据:哎呀(t1.c)

以下是关于代码的一些说明。首先,如Stevens 建议的[SR05],我们封装了线程创建和合并例程,以便在失败时退出。对于这样简单的程序,我们希望至少注意到发生了错误(如果发生了错误),但不做任何非常聪明的处理(只是退出)。因此,Pthread_create()只需调用pthread_create(),并确保返回码为0。如果不是,Pthread_create()就打印一条消息并退出。

其次,我们没有用两个独立的函数作为工作线程,只使用了一段代码,并向线程传入一个参数(在本例中是一个字符串),这样就可以让每个线程在打印它的消息之前,打印不同的字母。

最后,最重要的是,我们现在可以看看每个工作线程正在尝试做什么:向共享变量计数器添加一个数字,并在循环中执行1000 万(107)次。因此,预期的最终结果是:20000000。

我们现在编译并运行该程序,观察它的行为。有时候,一切如我们预期的那样:

prompt> gcc -o main main.c -Wall -pthread
prompt> ./main
main: begin (counter = 0)
A: begin
B: begin
A: done
B: done
main: done with both (counter = 20000000)

遗憾的是,即使是在单处理器上运行这段代码,也不一定能获得预期结果。有时会这样:

prompt> ./main
main: begin (counter = 0)
A: begin
B: begin
A: done
B: done
main: done with both (counter = 19345221)

让我们再试一次,看看我们是否疯了。毕竟,计算机不是应该产生确定的(deterministic)结果,像教授讲的那样?!也许教授一直在骗你?(大口地吸气)

prompt> ./main
main: begin (counter = 0)
A: begin
B: begin
A: done
B: done
main: done with both (counter = 19221041)

每次运行不但会产生错误,而且得到不同的结果!有一个大问题:为什么会发生这种情况?

提示:了解并使用工具

你应该学习使用新的工具,帮助你编程、调试和理解计算机系统。我们使用一个漂亮的工具,名为反汇编程序(disassembler)。如果对可执行文件运行反汇编程序,它会显示组成程序的汇编指令。例如,如果我们想要了解更新计数器的底层代码(如我们的例子),就运行objdump(Linux)来查看汇编代码:

prompt> objdump -d main

这样做会产生程序中所有指令的长列表,整齐地标明(特别是如果你使用-g 标志编译),其中包含程序中的符号信息。objdump 程序只是应该学习使用的许多工具之一。像gdb 这样的调试器,像valgrind或purify 这样的内存分析器,当然编译器本身也应该花时间去了解更多信息。工具用得越好,就可以建立更好的系统。