公司动态

操作系统笔记之临界区

📅 2026/7/15 0:57:27
操作系统笔记之临界区
操作系统笔记之临界区code review!文章目录操作系统笔记之临界区1.一句话描述临界区2.另外一句话描述临界区3.示例1.一句话描述临界区临界区Critical Section是指进程或线程中访问共享互斥资源的那段必须互斥执行的代码。2.另外一句话描述临界区临界区是指进程或线程中访问共享资源如共享变量、文件等的一段代码为避免竞态条件任意时刻只允许一个进程/线程进入执行。3.示例以下是一个使用 C 语言 POSIX 线程pthread互斥锁实现临界区保护的极简完整示例#includestdio.h#includepthread.hintcounter0;// 共享资源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。