Skip to content

Latest commit

ย 

History

History
86 lines (60 loc) ยท 3 KB

synchronous-asynchronous.md

File metadata and controls

86 lines (60 loc) ยท 3 KB

๐Ÿ’ป ๋™๊ธฐ(Synchronous)์™€ ๋น„๋™๊ธฐ(Asynchronous)


๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป ๋™๊ธฐ(Synchronous)๋ž€?

๋™๊ธฐ

  • ๋ง ๊ทธ๋Œ€๋กœ ๋™์‹œ์— ์ผ์–ด๋‚œ๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค.
  • ์š”์ฒญ์„ ๋ณด๋‚ธ ํ›„ ํ•ด๋‹น ์š”์ฒญ์˜ ์‘๋‹ต(=๊ฒฐ๊ณผ)์„ ๋ฐ›์•„์•ผ ๋‹ค์Œ ๋™์ž‘์„ ์‹คํ–‰ํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค.
  • ์„ค๊ณ„๊ฐ€ ๊ฐ„๋‹จํ•˜๊ณ  ์ง๊ด€์ ์ด์ง€๋งŒ ๊ฒฐ๊ณผ๋ฅผ ๋ณผ๋•Œ๊นŒ์ง€ ์•„๋ฌด๊ฒƒ๋„ ๋ชปํ•˜๊ณ  ๋Œ€๊ธฐํ•ด์•ผ ๋œ๋‹ค.
  • ์ฆ‰, ์š”์ฒญ์ด ๋“ค์–ด์˜จ ์ˆœ์„œ์— ๋งž๊ฒŒ ํ•˜๋‚˜์”ฉ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค. ์ˆœ์„œ์— ๋งž์ถฐ ์ง„ํ–‰๋œ๋‹ค๋Š” ์žฅ์ ์€ ์žˆ์ง€๋งŒ, ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์š”์ฒญ์„ ๋™์‹œ์— ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์—†๋‹ค.
  • ์‹ค์ œ cpu๊ฐ€ ๋Š๋ ค์ง€๋Š” ๊ฒƒ์€ ์•„๋‹ˆ์ง€๋งŒ, ์‹œ์Šคํ…œ์˜ ์ „์ฒด์ ์ธ ํšจ์œจ์ด ์ €ํ•˜๋œ๋‹ค๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค.

function func1() {
  console.log('func1');
  func2();
}

function func2() {
  console.log('func2');
  func3();
}

function func3() {
  console.log('func3');
}

func1(); //์ถœ๋ ฅ: func1 func2 func3
  • ์œ„์— ์˜ˆ์‹œ๋Š” ๋™๊ธฐ์‹์œผ๋กœ ๋™์ž‘ํ•˜๋Š” ์ฝ”๋“œ๋กœ, ์ˆœ์ฐจ์ ์œผ๋กœ ์‹คํ–‰๋œ๋‹ค.

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป ๋น„๋™๊ธฐ(Asynchronous)๋ž€?

๋น„๋™๊ธฐ

  • ๋ง๊ทธ๋Œ€๋กœ ๋™์‹œ์— ์ผ์–ด๋‚˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค.
  • ์š”์ฒญ์„ ๋ณด๋‚ธ ํ›„ ์‘๋‹ต๊ณผ ๊ด€๊ณ„์—†์ด ๋‹ค์Œ ๋™์ž‘์„ ์‹คํ–‰ํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค.
  • ๊ฒฐ๊ณผ๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋”๋ผ๋„ ๊ทธ ์‹œ๊ฐ„๋™์•ˆ ๋‹ค๋ฅธ ์ž‘์—…์ด ๊ฐ€๋Šฅํ•ด ์ž์›์˜ ํšจ์œจ์ ์ธ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜์ง€๋งŒ, ์„ค๊ณ„๊ฐ€ ๋™๊ธฐ์  ๋ฐฉ์‹๋ณด๋‹ค ๋ณต์žกํ•˜๋‹ค.

function func1() {
  console.log('func1');
  func2();
}

function func2() {
  setTimeout(function () {
    console.log('func2');
  }, 0);
  func3();
}

function func3() {
  console.log('func3');
}

func1(); //์ถœ๋ ฅ: func1 func3 func2

  • ์œ„์˜ ์˜ˆ์ œ๋Š” ๋น„๋™๊ธฐ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ์ฝ”๋“œ์ด๋‹ค. setTimeout ๋ฉ”์„œ๋“œ๊ฐ€ ๋Œ€ํ‘œ์ ์ธ ๋น„๋™๊ธฐ ํ•จ์ˆ˜์ด๋‹ค.
  1. ํ•จ์ˆ˜ func1 ํ˜ธ์ถœ๋˜๋ฉด ํ•จ์ˆ˜ func1์€ Call Stack์— ์Œ“์ธ๋‹ค.
  2. ํ•จ์ˆ˜ func1์€ ํ•จ์ˆ˜ func2์„ ํ˜ธ์ถœํ•˜๋ฏ€๋กœ ํ•จ์ˆ˜ func2๊ฐ€ Call Stack์— ์Œ“์ด๊ณ  setTimeout๋ฉ”์„œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋œ๋‹ค.
  3. setTimeout์˜ ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋Š” ์ฆ‰์‹œ ์‹คํ–‰๋˜์ง€ ์•Š๊ณ , ์ง€์ • ๋Œ€๊ธฐ ์‹œ๊ฐ„๋งŒํผ ๊ธฐ๋‹ค๋ฆฌ๋‹ค๊ฐ€ 'tick' ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ํ๋กœ ์ด๋™ํ•œ๋‹ค.
  4. Call Stack์ด ๋น„์–ด์กŒ์„ ๋•Œ Call Stack์œผ๋กœ ์ด๋™๋˜์–ด ์‹คํ–‰๋œ๋‹ค.

๋น„๋™๊ธฐ์ฒ˜๋ฆฌ๊ณผ์ •


์ฐธ๊ณ 

https://sinsomi.tistory.com/entry/%EC%8B%A0%EC%9E%85-%EA%B0%9C%EB%B0%9C%EC%9E%90-%EB%A9%B4%EC%A0%91-%EB%8F%99%EA%B8%B0%EC%99%80-%EB%B9%84%EB%8F%99%EA%B8%B0-%EA%B0%9C%EB%85%90-%EC%B4%88%EC%BD%94%EB%8D%94
https://velog.io/@dolarge/cs-%EB%8F%99%EA%B8%B0%EC%99%80-%EB%B9%84%EB%8F%99%EA%B8%B0
https://seunghyun90.tistory.com/51
https://webclub.tistory.com/605
https://private.tistory.com/24