1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
 
pthread_mutex_t mutex;
int global;
void * start(void * sid)
{
    for(int i = 0; i < 20; ++i)
    {
        //~ pthread_mutex_lock(&mutex);  // #1
        int j = global;
        //~ pthread_mutex_unlock(&mutex);// $1
        ++j;
        printf(".");
        fflush(stdout);
        sleep(1);
        //~ pthread_mutex_lock(&mutex); // #2
        global = j;
        //~ pthread_mutex_unlock(&mutex); // $2
    }
    return NULL;
}
int
main()
{
    pthread_t tid;
    pthread_mutex_init(&mutex, NULL);
    if(pthread_create(&tid, NULL, start, NULL))
    {
        printf("error creating thread.");
        abort();
    }
    for (int i = 0; i < 20; ++i)
    {
        //~ pthread_mutex_lock(&mutex); //#3
        ++global;
        //~ pthread_mutex_unlock(&mutex); // $3
        printf("o");
        fflush(stdout);
        sleep(1);
    }
    if(pthread_join(tid, NULL))
    {
        printf("error joining thread.");
        abort();
    }
    printf("%d\n", global);
    pthread_mutex_destroy(&mutex);
    return 0;
}

程序输出:
o.o.o.o.o.o.o.o..o.o.oo.o.o.o.o.o.o.o.o.21
为什么呢?
加上代码中注释掉的互斥锁1、2、3后,输出没有大的变化,只是global变成了20。再注释掉$1、#2,输出结果就正常了。

Tags: .
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

Be the first to comment on this entry.

Name(required)
Mail (required),(will not be published)

RFC: Request For Comments. Orz..

Website(recommended)