例如int *a int *b 分别指向两块内存,上面的值分别初始化为(200, 100) 线程A执行这样的一个操作:将*a的值减少50,*b的值增加50.
线程B执行:打印出(a 跟 b 指向的内存的值的和)。
如果串行运行:A: *a -= 50; *b += 50; B: printf("%d\n", *a + *b);
如果并发执行,则有可能会出现一下调度:*a -= 50; printf("%d\n", *a + *b); *b += 50;
因此我们可以引入互斥量,在对共享数据读写时进行锁操作,实现对内存的访问以互斥的形式进行。
-
#include <stdio.h>
-
#include <unistd.h>
-
#include <pthread.h>
-
#include<stdlib.h>
-
-
int a = 200;
-
int b = 100;
-
pthread_mutex_t lock;
-
-
void* ThreadA(void*argc)
-
{
-
printf("pthreadA is running\n");
-
pthread_mutex_lock(&lock); //锁
-
printf("pthreadA locked...\n");
-
a -= 50;
-
sleep(5); //执行到一半 使用sleep 放弃cpu调度
-
b += 50;
-
pthread_mutex_unlock(&lock);
-
printf("pthreadA unlocked...\n");
-
printf("pthreadA exit\n");
-
}
-
-
void* ThreadB(void*argc)
-
{
-
sleep(1); //放弃CPU调度 目的先让A线程运行。
-
printf("pthreadB is running\n");
-
//pthread_mutex_unlock(&lock);
-
//printf("pthreadB unlocked...\n");
-
pthread_mutex_lock(&lock);
-
printf("pthreadB locked...\n");
-
printf("%d\n", a + b);
-
pthread_mutex_unlock(&lock);
-
printf("pthreadB unlocked...\n");
-
printf("pthreadB exit\n");
-
}
-
-
int main()
-
{
-
pthread_t tida, tidb;
-
pthread_mutex_init(&lock, NULL);
-
pthread_create(&tida, NULL, ThreadA, NULL);
-
pthread_create(&tidb, NULL, ThreadB, NULL);
-
pthread_join(tida, NULL);
-
pthread_join(tidb, NULL);
-
exit(0);
-
}
运行结果:
[vibe@localhost code]$ ./a
pthreadA is running
pthreadA locked...
pthreadB is running
pthreadA unlocked...
pthreadA exit
pthreadB locked...
300
pthreadB unlocked...
pthreadB exit
阅读(1330) | 评论(0) | 转发(0) |