Software/Embedded system

The Keyword (feat. static, volatile)

neovaga 2021. 5. 20. 23:55

1. static ( global /function): only visible within its own translation unit.

   static (local variable): persistent across function calls and only visible within its function. Need the initialization.

 

Static 은 메모리 구조에서 Data 영역에 저장이 된다. 프로그램 시작과 동시에 할당이 되고 프로그램이 종료되어야 메모리에서 지워 진다. 

 

2. volatile: The volatile keyword prevents the compiler from performing optimization on code involving volatile objects, thus ensuring that each volatile variable assignment and read has corresponding memory access. Without the volatile keyword, the compiler knows a variable does not need to be reread from memory at each use, because there should not be any writes to its memory location from any other thread or process

 

Complier가 최적화를 통해서 불필요하다고 생각하는 부분을 동작을 하지 않게 하는 것을 방지 하는 역활을 한다. multi thread 를 사용하는 경우에 complier가 interrupt 가 발생하는 경우까지 예상을 못하는 경우가 있다. 

compile 의 최적화를 통해서 속도를 올리는 이유가 되는데 volatile를 다 쓰게 되면 이런 benefit이 사라지게 된다. 

 

해당 코드가 참 좋은 예제가 된다. line 22 부분이 최적화 옵션으로 compile를 해버리면 항상 True로 인식이 되어 버리게 되어서 While 에 영원히 빠져 있게 되어 버린다. Thread에서 tfunc()을 실행하는 부분이 의미가 없게 되어 버린다. 

 

//예제 참조하는 유투부: 

https://www.youtube.com/watch?v=6tIWFEzzx9I&t=62s

반응형

'Software > Embedded system' 카테고리의 다른 글

exec() System call concept  (0) 2021.06.27
fork() system call concept  (0) 2021.06.27
Memory - stack and heap  (0) 2021.05.26
Priority Inversion (feat. Embeded system)  (0) 2021.05.23
Threads Concept  (0) 2021.05.23