两个并行运行的程序片断,如线程,同时读写同一块内存,其结果是不确定的。这时候我们需要互斥锁,保证一个线程先读写完,然后另一个线程才可以读写。
1 没有使用mutex的例子
# cat mutex-example-1.c
#include <stdio.h> //ptrinf
#include <pthread.h> //pthread_xxx
#include <unistd.h> //sleep
int global_para = 0;
void *do_sth(void *p)
{
long i = (long)p;
printf("thread %d - start to read\n", i);
int temp = global_para;
sleep(2);
printf("thread %d - end of reading\n", i);
printf("thread %d - start to write\n", i);
sleep(2);
global_para = temp + (int)i;
printf("thread %d - end of reading\n", i);
}
int main()
{
pthread_t t1, t2;
pthread_create(&t1, 0, do_sth, (void *)1);
pthread_create(&t2, 0, do_sth, (void *)2);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("-- global_para is %d --\n", global_para);
}
# gcc mutex-example-1.c -o mutex-example-1 -lpthread && ./mutex-example-1
thread 2 - start to read
thread 1 - start to read
thread 1 - end of reading
thread 1 - start to write
thread 2 - end of reading
thread 2 - start to write
thread 1 - end of reading
thread 2 - end of reading
-- global_para is 2 --
每一次的运行结果都可能不一样。
# gcc mutex-example-1.c -o mutex-example-1 -lpthread && ./mutex-example-1
thread 2 - start to read
thread 1 - start to read
thread 2 - end of reading
thread 2 - start to write
thread 1 - end of reading
thread 1 - start to write
thread 2 - end of reading
thread 1 - end of reading
-- global_para is 1 --
2 使用mutex的例子
# cat mutex-example-2.c
#include <stdio.h> //ptrinf,perror
#include <stdlib.h> //exit
#include <pthread.h> //pthread_xxx
#include <unistd.h> //sleep
int global_para = 0;
pthread_mutex_t lock;
void die(char *s)
{
perror(s);
exit(1);
}
void *do_sth(void *p)
{
long i = (long)p;
pthread_mutex_lock(&lock);
printf("thread %d - start to read\n", i);
int temp = global_para;
sleep(2);
printf("thread %d - end of reading\n", i);
printf("thread %d - start to write\n", i);
sleep(2);
global_para = temp + (int)i;
printf("thread %d - end of reading\n", i);
pthread_mutex_unlock(&lock);
}
int main()
{
pthread_t t1, t2;
if (pthread_mutex_init(&lock, NULL) != 0)
{
die("pthread_mutex_init()");
}
pthread_create(&t1, 0, do_sth, (void *)1);
pthread_create(&t2, 0, do_sth, (void *)2);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_mutex_destroy(&lock);
printf("-- global_para is %d --\n", global_para);
}
# gcc mutex-example-2.c -o mutex-example-2 -lpthread && ./mutex-example-2
thread 2 - start to read
thread 2 - end of reading
thread 2 - start to write
thread 2 - end of reading
thread 1 - start to read
thread 1 - end of reading
thread 1 - start to write
thread 1 - end of reading
-- global_para is 3 --
因为是串行读写,程序运行慢了很多,但结果正确了。
参考
http://www.thegeekstuff.com/2012/05/c-mutex-examples/?refcom
网友评论