> For the complete documentation index, see [llms.txt](https://kukingclass.gitbook.io/computerscience/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kukingclass.gitbook.io/computerscience/operating-system/race-condition.md).

# Race Condition

## Race Condition (경쟁 상태) 이란?

* 두 개 이상의 프로세스가 공통 자원을 동시에 읽거나 쓰는 동작을 할 때, 공용 데이터에 대한 접근 순서에 따라 실행 결과가 같지 않고 달라지는 상황을 뜻한다.
* Race의 뜻 그대로, 두개의 스레드가 하나의 자원을 놓고 서로 사용하려고 경쟁하는 상황을 말한다.

## Race Condition 예시

* 생산자 - 소비자 모델

![image](https://user-images.githubusercontent.com/63101979/192706385-1d782301-296c-4cb0-b987-91b6aff49bae.png)

위 그림과 같이 A와 B 프로세스가 같은 버퍼를 공유하고 있는 상태이고, A는 공유하고 있는 버퍼에 데이터를 채워 넣고, B는 데이터를 가져간다.\
( 버퍼가 가득 차있으면 A는 빈 공간이 생길 때까지 대기하고, 버퍼가 텅 비어있으면 B는 A가 데이터를 넣어줄 때까지 대기한다. )

```
여기서 두 프로세스는 counter라는 int형 변수를 이용해 버퍼에 얼만큼의 데이터가 존재하는지 파악한다.  
이러한 상황에서 A는 counter++, B는 counter-- 을 실행하게 된다.  

- 예상대로 A가 먼저 데이터를 채워넣고, B가 데이터를 가져가는 경우 
→ counter 값 유지  

- 하지만 A가 호출되고 바로 직후 B가 실행되어, A의 연산이 끝나기 전에 B가 실행되어버리는 경우 
→ A와 B의 counter 값이 서로 달라 시스템에 오류 발생
```

이처럼 공용 데이터에 대한 접근 순서에 따라 실행 결과가 동일하지 않는 상황이 Race Condition이다.

## 발생 환경

### 1. 멀티 프로세스 / 스레드

* 멀티 프로세스 환경에서 2개의 PCU가 동시에 커널 내부의 공유 데이터에 접근하여 조작하는 경우
* 멀티 스레드 환경에서 공통 자원을 병행하여 작업할 때

→ 해결법 : 커널 내부에 있는 각 공유 데이터에 접근할 때마다, 그 데이터에 대한 lock/unlock을 한다.

### 2. 커널 작업

* 커널 모드에서 데이터를 로드하여 작업을 수행하다가 인터럽트가 발생하여 같은 데이터를 조작하는 경우

→ 해결법 : 커널모드에서 작업을 수행하는 동안, 인터럽트를 disable 시켜 CPU 제어권을 가져가지 못하도록 한다.

### 3. 프로세스의 시스템콜

* 프로세스가 시스템콜을 하여 커널모드로 진입하여 작업을 수행하는 도중 문맥 교환이 발생하는 경우
* 프로세스가 데이터를 조작하는 중, 시간이 초과되어 CPU 제어권이 다른 프로세스로 넘어가 같은 데이터를 조작하는 경우

→ 해결법 : 프로세스가 커널모드에서 작업을 하는 경우 시간이 초과되어도 CPU 제어권을 다른 프로세스에게 넘겨주지 못하도록 한다.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://kukingclass.gitbook.io/computerscience/operating-system/race-condition.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
