操作系统笔记之临界区
code review!
文章目录
- 操作系统笔记之临界区
- 1.一句话描述临界区
- 2.另外一句话描述临界区
- 3.示例
1.一句话描述临界区
临界区(Critical Section)是指进程或线程中访问共享互斥资源的那段必须互斥执行的代码。
2.另外一句话描述临界区
临界区是指进程或线程中访问共享资源(如共享变量、文件等)的一段代码,为避免竞态条件,任意时刻只允许一个进程/线程进入执行。
3.示例
以下是一个使用 C 语言 + POSIX 线程(pthread)互斥锁实现临界区保护的极简完整示例:
#include<stdio.h>#include<pthread.h>intcounter=0;// 共享资源pthread_mutex_tlock;// 互斥锁void*increment(void*arg){pthread_mutex_lock(&lock);// 进入临界区counter++;// 访问共享资源pthread_mutex_unlock(&lock);// 离开临界区returnNULL;}intmain(){pthread_tt1,t2;pthread_mutex_init(&lock,NULL);pthread_create(&t1,NULL,increment,NULL);pthread_create(&t2,NULL,increment,NULL);pthread_join(t1,NULL);pthread_join(t2,NULL);printf("counter = %d\n",counter);// 输出结果应为 2pthread_mutex_destroy(&lock);return0;}说明:
counter是两个线程共享的资源。pthread_mutex_lock和pthread_mutex_unlock之间的代码就是临界区。- 互斥锁保证任意时刻只有一个线程能执行
counter++,避免竞态条件,确保最终结果正确为2。