SlideShare une entreprise Scribd logo
1  sur  54
Erlang 2008 아꿈사Annual Summary 현수명 soomong80@gmail.com http://soomong.tistory.com
30분 동안 Erlang에서 가장 중요한것들만 효과적으로 전달하자. Erlang언어를 처음 접하는 사람들에게 새로운 언어의 장점을 소개함으로써 사고의 폭을 넓힐 수 있다면 성공.
Erlang? 병행성 멀티코어 분산 무정지
Erlang ? Ericsson 에서 초기개발되어 사용 함수형 언어 가운데 산업에서 쓰이는 유일한 언어 자체 Erlang shell 지원 Everything is a process. 운영체제의 프로세스가 아니라 얼랭 언어 자체의 프로세스.
$ erl 1> 1+2. 3 2> A = 5. 5 3> X = hello. hello 4> X. hello
애텀 불변의 값. 1> hello. hello 2> rectangle. rectangle
fun 익명함수 F = fun(X) -> (2 * X) end. 인자 X 가 들어왔을때 2*X 를 수행해서 결과를 돌려주는 함수 결과값을 F 에 넣는것이 아니라함수자체를 F 에 bound 하는것을의미
$ erl 1> F = fun(X) -> (2 * X) end. #Fun<erl_eval.6.5634564> 2> F(10). 20 3> Double = F. #Fun<erl_eval.6.5634564> 4> Double(5). 10 5> F(5). 10
튜플 정해진 수의 항목을 하나의 개체로 그룹핑 C 의 구조체와 비슷. 익명 구조체 1> Rect = {rect, 10, 45}. {rect, 10, 45} 2> {rect, X, Y} = Rect. {rect, 10, 45} 3> X. 10 4> Y. 45 {rect, 10, 45} {rect,  X , Y }
리스트 [ Head | Tail ] 1> L = [1,2,3,4]. [1,2,3,4] 2> [H|T] = L. [1,2,3,4] 3> H. 1 4> T. [2,3,4] 5> [H1|T1] = T. [2,3,4] 6> H1. 2 7> T1. [3,4,] [1 , 2,3,4] [H|   T  ] [2 , 3,4] [H1| T1 ]
Factorial fact.erl -module(fact). -export([fac/1]). fac(0) -> 1; fac(N) -> N * fac(N-1).
Quicksort quicksort.erl -module(quicksort).  -export([quicksort/1]). quicksort([]) -> [];  quicksort([Pivot|Rest]) -> quicksort([Front || Front <- Rest, Front < Pivot])      ++ [Pivot] ++  quicksort([Back || Back <- Rest, Back >= Pivot]). 짧은 코드!
Erlang? 병행성 멀티코어 분산 무정지
The Free Lunch Is Over The Free Lunch? The Free Performance Lunch! 싱글코어CPU 의 발전한계. 멀티코어 CPU Concurrency is the next major revolution in how we write software. -Herb Sutter
병행성 지향 프로그래밍 Concurrency-oriented programming 처음부터 병행성을 고려해서 만든 언어. 공유 메모리가 없음 잠금 매커니즘필요없음 쉽게 병행 프로그래밍 가능
단일 할당 변수 1> X. 1: variable ‘X' is unbound 2> X = 50. 50 3> X = 23. ** exception error: no match of right hand side value 23 변수가 아니라 write-once 변수 즉 한번만 bound 를 할 수 있음
패턴매칭 X = 50. = 은 할당연산자가 아니라 패턴매칭연산자. 오른쪽을 평가해서 그 결과를 왼쪽에 있는 패턴과 매치하라는 뜻.
왜 단일 할당이 프로그램을 더 낫게 만드는가? 변수의 값을 바꿀수 있다? 누가 언제 바꿨는지 깔끔하게 알기힘듬.  복잡한 잠금 매커니즘 필요. 변수의 값을 바꿀수 없다? 불변상태의 메모리는 read 만 가능. 잠금 매커니즘이필요없다. 즉 쉬운 병행 프로그래밍 가능 어떻게? 프로세스 메시지 전달 방식으로.
Pure message passing language 순수 메시지 전달 언어 명령어 3개로병행프로그래밍 가능 spawn : 프로세스 생성 ! (send) : 메시지 보내기 receive : 메시지 받기
$ erl 1> Pid = spawn(fun area:loop/0). <0.45.0> 2> Pid! {rect, 6, 10}. rect : 60 3> Pid! {circle, 5}. circle : 78.5 4> Pid! {triangle, 2, 4, 5}. what is it? triangle?
area.erl -module(area). -export([loop/0]). loop()-> receive 		{rect, Width, Ht} -> io:format(“rect : ~p~n”, [Width * Ht]), 			loop(); 		{circle, R} -> io:format(“circle : ~p~n”, [3.14 * R * R]), 			loop(); 		Other -> io:format(“what is it? ~p?~n”, [Other]), 			loop() 	end.
Erlang process OS process 와는 다른얼랭자체process 프로세스마다 mailbox 를 하나씩 가짐 프로세스에 메시지를 보내면 mailbox 로 들어가고 receive 문을 평가할때mailbox 에서 메시지를 하나씩 꺼내서 처리
공유메모리 없고 잠금도 필요없으므로Easy 쉬운병행 프로그래밍 가능
Erlang? 병행성 멀티코어 분산 무정지
멀티코어 프로그래밍 Multicore programming 쉬운 병행 프로그래밍 덕분에 멀티코어도 역시 쉽게 가능 동일머신의 멀티코어 분산처리 프로세스를 spawn 해서 처리하고 결과모으기
-module(pmap). -export([map/2,pmap/2]). map(_, []) -> [];    map(F, [H|T]) -> [F(H) | map(F,T)].   pmap(F, L) ->     	S = self(), 	Ref = erlang:make_ref(),     Pids = map( fun(I) -> spawn(fun() -> do_f(S, Ref, F, I) end) end , L ),    	gather(Pids, Ref).    do_f(Parent, Ref, F, I) ->                           	Parent ! {self(), Ref, (catch F(I))}.    gather([Pid|T], Ref) ->    	receive 		{Pid, Ref, Ret} -> [Ret|gather(T, Ref)]    	end;    gather([], _) -> [].
싱글코어 프로그래밍 map(_, []) -> [];    map(F, [H|T]) -> [F(H) | map(F,T)]. 1> F = fun(X) -> (2 * X) end. #Fun<erl_eval.6.5634564> 2> F(10). 20 3> pmap:map(F,[1,2,3,4,5]). [2,4,6,8,10]
멀티코어 프로그래밍 1> F = fun(X) -> (2 * X) end. #Fun<erl_eval.6.5634564> 2> F(10). 20 3> pmap:pmap(F,[1,2,3,4,5]). [2,4,6,8,10] process 5개가 각각 인수를 병렬로 평가
멀티코어 프로그래밍 pmap(F, L) ->     	S = self(), 	Ref = erlang:make_ref(),     Pids = map( fun(I) -> spawn(fun() -> do_f(S, Ref, F, I) end) end , L ),    	gather(Pids, Ref).    do_f(Parent, Ref, F, I) ->                           	Parent ! {self(), Ref, (catch F(I))}.    gather([Pid|T], Ref) ->    	receive 		{Pid, Ref, Ret} -> [Ret|gather(T, Ref)]    	end;    gather([], _) -> [].
pmap:pmap(F,[1,2,3,4,5]). Pids = map( fun(I) ->  		spawn(fun() -> do_f(S, Ref, F, I) end)  	end , L ), do_f F(I) spawn pmap do_f(Parent, Ref, F, I) ->                           	Parent ! {self(), Ref, (catch F(I))}.  Parent ! 2 gather([Pid|T], Ref) ->    	receive 		{Pid, Ref, Ret} ->  			[Ret|gather(T, Ref)]    	end;    gather([], _) -> [].  반복
쉬운 병행프로그래밍 덕분에Easy 쉬운멀티코어 프로그래밍 가능
Erlang? 병행성 멀티코어 분산 무정지
분산? Distributed Programming 멀티코어 프로그래밍에서 spawn 으로 생성한 프로세스들이 동일한 머신에 있을필요없음. Erlang node 와 얼랭 표준 라이브러리를 이용
여러머신의 네트워크 분산처리 Erlang node 간의 message 전달방식으로 쉬운분산처리 가능 Erlang node 란 이름을 가지고 있는 Erlang runtime system 이름을 가진 Erlang shell
여러머신의 네트워크 분산처리 server 라는 이름의 Erlang node 실행 $erl –sname server (server@serverhost) 1> 쿠키 각 node 는 쿠키를 한개씩 가지고있고 쿠키가 같은노드끼리만 통신가능 $erl –sname client –setcookieabc (client@clienthost) 1>
-module(mod). -export([F/1]). F(X) -> 2*X. $erl –sname server (server@serverhost) 1> rpc:call(client@clienthost, mod, F, [2]). 4 Server Node rpc:call 4 F(2) Client Node $erl –sname client (client@clienthost) 1>
Erlang node와 얼랭 표준 라이브러리를 이용하여Easy 쉬운분산 프로그래밍 가능
Erlang? 병행성 분산 멀티코어 무정지
무정지? 멈추지 않는 서비스 Server down! 다른서버가 작업을 이어서 수행 무정지는프로세스간의 link 기능으로 쉽게 구현가능
Process spawn 내가 생성한 프로세스가 멈춰도 난 모름 Pid = spawn(fun() -> … end) 내가 생성한 프로세스가 멈추면 나도 멈출래 Pid = spawn_link(fun() -> … end) 내가 생성한 프로세스가 멈추면 내가 해결해줄께 process_flag(trap_exit, true), Pid = spawn_link(fun() -> … end)
Pid = spawn(fun() -> … end) Pid = spawn_link(fun() -> … end) process_flag(trap_exit, true), Pid = spawn_link(fun() -> … end) A B
-module(fault). -export([start/0]). start() -> process_flag(trap_exit, true), spawn_link(fun() -> work() end), 	loop(). work() ->  	sleep(5000), 	2/0. loop() -> 	receive 		{'EXIT',SomePid,Reason} -> io:format("system down !!") 	end. sleep(T) -> 	receive 	after T -> true 	end.
(server@host)1> fault:start(). …5초후… system down !! =ERROR REPORT==== 7-Jan-2009::23:56:29 === Error in process <0.67.0> on node 'server@host' with exit value: {badarith,[{fault,work,0}]} (server@host)2>
-module(fault). -export([start/0]). start() -> process_flag(trap_exit, true), spawn_link(fun() -> work() end), 	loop(). work() ->  	sleep(5000), 	2/0. loop() -> 	receive 		{'EXIT',SomePid,Reason} -> io:format("system down !!"), start(). 	end. sleep(T) -> 	receive 	after T -> true 	end.
(server@host)1> fault:start(). …5초후… system down !! =ERROR REPORT==== 7-Jan-2009::23:56:29 === Error in process <0.67.0> on node 'server@host' with exit value: {badarith,[{fault,work,0}]} …5초후… system down !! =ERROR REPORT==== 7-Jan-2009::23:56:34 === Error in process <0.68.0> on node 'server@host' with exit value: {badarith,[{fault,work,0}]}
process link 기능을 이용하여Easy 쉬운무정지 프로그래밍 가능
Hotcode swapping Dynamic Code Loading 기능 우리가 특정모듈의 특정함수를 호출할때항상 가장 최신 버전의 함수가 호출됨
-module(hotcode). -export([start/0]). start() ->  	spawn(fun() -> loop() end). loop() -> 	sleep(1000), 	Val = a:x(), io:format("a:x() : ~p~n", [Val]), 	loop(). sleep(T) -> 	receive 	after T -> true 	end. -module(a). -export([x/0]). x() -> 1.
1> c(hotcode). {ok,hotcode} 2> hotcode:start(a). <0.49.0> a:x() : 1 a:x() : 1 a:x() : 1 -module(a). -export([x/0]). x() -> 1. -module(a). -export([x/0]). x() -> 2. 3> c(a). {ok,a} a:x() : 2 a:x() : 2
동적 코드 로딩WoW 이런것도 가능
Erlang? 애텀, fun, 튜플, 리스트 병행성 공유메모리가 없음 – 잠금필요없음  spawn, ! , receive 3개 명령어 멀티코어  process 여러 개 spawn 해서 처리하고 취합 분산 Erlang node 와 표준 라이브러리 rpc 무정지  process link
언어의 한계가  곧 자기세계의 한계이다.  - 루트비히비트켄슈타인
reference Programming Erlang  –인사이트- http://www.gotw.ca/publications/concurrency-ddj.htm -Herb Sutter- 실용주의프로그래머 –인사이트-

Contenu connexe

Tendances

Python3 10장 문자열이야기
Python3 10장 문자열이야기Python3 10장 문자열이야기
Python3 10장 문자열이야기
Jihoon Kong
 
파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301
Yong Joon Moon
 
2012 Ds D2 03
2012 Ds D2 032012 Ds D2 03
2012 Ds D2 03
chl132435
 

Tendances (20)

포인터의 기초(1)
포인터의 기초(1)포인터의 기초(1)
포인터의 기초(1)
 
Python3 10장 문자열이야기
Python3 10장 문자열이야기Python3 10장 문자열이야기
Python3 10장 문자열이야기
 
정규표현식 Regular expression (regex)
정규표현식 Regular expression (regex)정규표현식 Regular expression (regex)
정규표현식 Regular expression (regex)
 
Python3 brief summary
Python3 brief summaryPython3 brief summary
Python3 brief summary
 
파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301
 
Python datatype
Python datatypePython datatype
Python datatype
 
정규표현식(Regular expressions)
정규표현식(Regular expressions)정규표현식(Regular expressions)
정규표현식(Regular expressions)
 
Python Sympy 모듈 이해하기
Python Sympy 모듈 이해하기Python Sympy 모듈 이해하기
Python Sympy 모듈 이해하기
 
Regex
RegexRegex
Regex
 
파이썬정리 20160130
파이썬정리 20160130파이썬정리 20160130
파이썬정리 20160130
 
자료구조03
자료구조03자료구조03
자료구조03
 
파이썬 함수
파이썬 함수파이썬 함수
파이썬 함수
 
텐서플로우 기초 이해하기
텐서플로우 기초 이해하기 텐서플로우 기초 이해하기
텐서플로우 기초 이해하기
 
2012 Ds D2 03
2012 Ds D2 032012 Ds D2 03
2012 Ds D2 03
 
python 수학이해하기
python 수학이해하기python 수학이해하기
python 수학이해하기
 
Reflect package 사용하기
Reflect package 사용하기Reflect package 사용하기
Reflect package 사용하기
 
모두의 JIT 컴파일러
모두의 JIT 컴파일러모두의 JIT 컴파일러
모두의 JIT 컴파일러
 
Python vs Java @ PyCon Korea 2017
Python vs Java @ PyCon Korea 2017Python vs Java @ PyCon Korea 2017
Python vs Java @ PyCon Korea 2017
 
Ruby Enumerator(루비 열거자) 이해하기
Ruby Enumerator(루비 열거자) 이해하기Ruby Enumerator(루비 열거자) 이해하기
Ruby Enumerator(루비 열거자) 이해하기
 
파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409
 

En vedette (7)

Scalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed SystemsScalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed Systems
 
Dependency Breaking Techniques
Dependency Breaking TechniquesDependency Breaking Techniques
Dependency Breaking Techniques
 
아마존 게임엔진:Lumberyard :: Patel Pratik :: Gaming on AWS 2016
아마존 게임엔진:Lumberyard :: Patel Pratik :: Gaming on AWS 2016아마존 게임엔진:Lumberyard :: Patel Pratik :: Gaming on AWS 2016
아마존 게임엔진:Lumberyard :: Patel Pratik :: Gaming on AWS 2016
 
[IGC 2016] 아마존 구승모 - 게임 제작을 위한 Amazon의 편리한 도구들 (게임리프트와 럼버야드)
[IGC 2016] 아마존 구승모 - 게임 제작을 위한 Amazon의 편리한 도구들 (게임리프트와 럼버야드)[IGC 2016] 아마존 구승모 - 게임 제작을 위한 Amazon의 편리한 도구들 (게임리프트와 럼버야드)
[IGC 2016] 아마존 구승모 - 게임 제작을 위한 Amazon의 편리한 도구들 (게임리프트와 럼버야드)
 
아마존의 관리형 게임 플랫폼 활용하기: GameLift (Deep Dive) :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS ...
아마존의 관리형 게임 플랫폼 활용하기: GameLift (Deep Dive) :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS ...아마존의 관리형 게임 플랫폼 활용하기: GameLift (Deep Dive) :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS ...
아마존의 관리형 게임 플랫폼 활용하기: GameLift (Deep Dive) :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS ...
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11
 
[1116 박민근] c++11에 추가된 새로운 기능들
[1116 박민근] c++11에 추가된 새로운 기능들[1116 박민근] c++11에 추가된 새로운 기능들
[1116 박민근] c++11에 추가된 새로운 기능들
 

Similaire à Erlang

이산치 과제7
이산치 과제7이산치 과제7
이산치 과제7
mil23
 
2012 Dm A0 07 Pdf
2012 Dm A0 07 Pdf2012 Dm A0 07 Pdf
2012 Dm A0 07 Pdf
kd19h
 
2012 Dm A0 07 Pdf
2012 Dm A0 07 Pdf2012 Dm A0 07 Pdf
2012 Dm A0 07 Pdf
jinwookhong
 
H3 2011 파이썬으로 클라우드 하고 싶어요
H3 2011 파이썬으로 클라우드 하고 싶어요H3 2011 파이썬으로 클라우드 하고 싶어요
H3 2011 파이썬으로 클라우드 하고 싶어요
KTH
 
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
KTH, 케이티하이텔
 
2012 Ds A1 05
2012 Ds A1 052012 Ds A1 05
2012 Ds A1 05
seonhyung
 
You can read go code
You can read go codeYou can read go code
You can read go code
Homin Lee
 
2012 Ds B1 01
2012 Ds B1 012012 Ds B1 01
2012 Ds B1 01
seonhyung
 
2012 Ds B2 02 Pdf
2012 Ds B2 02 Pdf2012 Ds B2 02 Pdf
2012 Ds B2 02 Pdf
kd19h
 
2012 Ds B2 02
2012 Ds B2 022012 Ds B2 02
2012 Ds B2 02
chl132435
 
2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf
kd19h
 
2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf
jinwookhong
 
Design Pattern In Functional Language
Design Pattern In Functional LanguageDesign Pattern In Functional Language
Design Pattern In Functional Language
SH Park
 

Similaire à Erlang (20)

이산치 과제7
이산치 과제7이산치 과제7
이산치 과제7
 
2012 Dm A0 07 Pdf
2012 Dm A0 07 Pdf2012 Dm A0 07 Pdf
2012 Dm A0 07 Pdf
 
2012 Dm A0 07 Pdf
2012 Dm A0 07 Pdf2012 Dm A0 07 Pdf
2012 Dm A0 07 Pdf
 
현재 자바스크립트 표준은 어디쯤
현재 자바스크립트 표준은 어디쯤 현재 자바스크립트 표준은 어디쯤
현재 자바스크립트 표준은 어디쯤
 
2011 H3 컨퍼런스-파이썬으로 클라우드 하고 싶어요
2011 H3 컨퍼런스-파이썬으로 클라우드 하고 싶어요2011 H3 컨퍼런스-파이썬으로 클라우드 하고 싶어요
2011 H3 컨퍼런스-파이썬으로 클라우드 하고 싶어요
 
H3 2011 파이썬으로 클라우드 하고 싶어요
H3 2011 파이썬으로 클라우드 하고 싶어요H3 2011 파이썬으로 클라우드 하고 싶어요
H3 2011 파이썬으로 클라우드 하고 싶어요
 
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
H3 2011 파이썬으로 클라우드 하고 싶어요_분산기술Lab_하용호
 
TABLE ACCESS 패턴을 이용한 SQL 튜닝_Wh oracle
TABLE ACCESS 패턴을 이용한 SQL 튜닝_Wh oracleTABLE ACCESS 패턴을 이용한 SQL 튜닝_Wh oracle
TABLE ACCESS 패턴을 이용한 SQL 튜닝_Wh oracle
 
자구2번
자구2번자구2번
자구2번
 
2012 Ds A1 05
2012 Ds A1 052012 Ds A1 05
2012 Ds A1 05
 
You can read go code
You can read go codeYou can read go code
You can read go code
 
2012 Ds B1 01
2012 Ds B1 012012 Ds B1 01
2012 Ds B1 01
 
자구3번
자구3번자구3번
자구3번
 
2012 Ds B2 02 Pdf
2012 Ds B2 02 Pdf2012 Ds B2 02 Pdf
2012 Ds B2 02 Pdf
 
2012 Ds B2 02
2012 Ds B2 022012 Ds B2 02
2012 Ds B2 02
 
제5회 D2 CAMPUS SEMINAR - Go gopher 길들이기
제5회 D2 CAMPUS SEMINAR - Go gopher 길들이기제5회 D2 CAMPUS SEMINAR - Go gopher 길들이기
제5회 D2 CAMPUS SEMINAR - Go gopher 길들이기
 
2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf
 
2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf
 
Design Pattern In Functional Language
Design Pattern In Functional LanguageDesign Pattern In Functional Language
Design Pattern In Functional Language
 
Go
GoGo
Go
 

Plus de hyun soomyung

Plus de hyun soomyung (20)

아꿈사 매니저소개
아꿈사 매니저소개아꿈사 매니저소개
아꿈사 매니저소개
 
HTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,AudioHTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,Audio
 
Hybrid app
Hybrid appHybrid app
Hybrid app
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
MapReduce
MapReduceMapReduce
MapReduce
 
MongoDB
MongoDBMongoDB
MongoDB
 
The Art of Computer Programming 2.4 다중연결구조
The Art of Computer Programming 2.4 다중연결구조The Art of Computer Programming 2.4 다중연결구조
The Art of Computer Programming 2.4 다중연결구조
 
The Art of Computer Programming 2.3.2 Tree
The Art of Computer Programming 2.3.2 TreeThe Art of Computer Programming 2.3.2 Tree
The Art of Computer Programming 2.3.2 Tree
 
Design Pattern - Multithread Ch10
Design Pattern - Multithread Ch10Design Pattern - Multithread Ch10
Design Pattern - Multithread Ch10
 
The Art of Computer Programming 1.3.2 MIXAL
The Art of Computer Programming 1.3.2 MIXALThe Art of Computer Programming 1.3.2 MIXAL
The Art of Computer Programming 1.3.2 MIXAL
 
The Art of Computer Programming 1.2.5
The Art of Computer Programming 1.2.5The Art of Computer Programming 1.2.5
The Art of Computer Programming 1.2.5
 
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
 
Clojure Chapter.6
Clojure Chapter.6Clojure Chapter.6
Clojure Chapter.6
 
프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장
 
[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술
 
실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부
 
xUnitTestPattern/chapter8
xUnitTestPattern/chapter8xUnitTestPattern/chapter8
xUnitTestPattern/chapter8
 
예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법
 
프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?
 
5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)
 

Dernier

Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)
Wonjun Hwang
 
Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)
Wonjun Hwang
 

Dernier (6)

캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
 
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)
 
Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)
 

Erlang

  • 1. Erlang 2008 아꿈사Annual Summary 현수명 soomong80@gmail.com http://soomong.tistory.com
  • 2. 30분 동안 Erlang에서 가장 중요한것들만 효과적으로 전달하자. Erlang언어를 처음 접하는 사람들에게 새로운 언어의 장점을 소개함으로써 사고의 폭을 넓힐 수 있다면 성공.
  • 4. Erlang ? Ericsson 에서 초기개발되어 사용 함수형 언어 가운데 산업에서 쓰이는 유일한 언어 자체 Erlang shell 지원 Everything is a process. 운영체제의 프로세스가 아니라 얼랭 언어 자체의 프로세스.
  • 5. $ erl 1> 1+2. 3 2> A = 5. 5 3> X = hello. hello 4> X. hello
  • 6. 애텀 불변의 값. 1> hello. hello 2> rectangle. rectangle
  • 7. fun 익명함수 F = fun(X) -> (2 * X) end. 인자 X 가 들어왔을때 2*X 를 수행해서 결과를 돌려주는 함수 결과값을 F 에 넣는것이 아니라함수자체를 F 에 bound 하는것을의미
  • 8. $ erl 1> F = fun(X) -> (2 * X) end. #Fun<erl_eval.6.5634564> 2> F(10). 20 3> Double = F. #Fun<erl_eval.6.5634564> 4> Double(5). 10 5> F(5). 10
  • 9. 튜플 정해진 수의 항목을 하나의 개체로 그룹핑 C 의 구조체와 비슷. 익명 구조체 1> Rect = {rect, 10, 45}. {rect, 10, 45} 2> {rect, X, Y} = Rect. {rect, 10, 45} 3> X. 10 4> Y. 45 {rect, 10, 45} {rect, X , Y }
  • 10. 리스트 [ Head | Tail ] 1> L = [1,2,3,4]. [1,2,3,4] 2> [H|T] = L. [1,2,3,4] 3> H. 1 4> T. [2,3,4] 5> [H1|T1] = T. [2,3,4] 6> H1. 2 7> T1. [3,4,] [1 , 2,3,4] [H| T ] [2 , 3,4] [H1| T1 ]
  • 11. Factorial fact.erl -module(fact). -export([fac/1]). fac(0) -> 1; fac(N) -> N * fac(N-1).
  • 12. Quicksort quicksort.erl -module(quicksort). -export([quicksort/1]). quicksort([]) -> []; quicksort([Pivot|Rest]) -> quicksort([Front || Front <- Rest, Front < Pivot]) ++ [Pivot] ++ quicksort([Back || Back <- Rest, Back >= Pivot]). 짧은 코드!
  • 13. Erlang? 병행성 멀티코어 분산 무정지
  • 14. The Free Lunch Is Over The Free Lunch? The Free Performance Lunch! 싱글코어CPU 의 발전한계. 멀티코어 CPU Concurrency is the next major revolution in how we write software. -Herb Sutter
  • 15. 병행성 지향 프로그래밍 Concurrency-oriented programming 처음부터 병행성을 고려해서 만든 언어. 공유 메모리가 없음 잠금 매커니즘필요없음 쉽게 병행 프로그래밍 가능
  • 16. 단일 할당 변수 1> X. 1: variable ‘X' is unbound 2> X = 50. 50 3> X = 23. ** exception error: no match of right hand side value 23 변수가 아니라 write-once 변수 즉 한번만 bound 를 할 수 있음
  • 17. 패턴매칭 X = 50. = 은 할당연산자가 아니라 패턴매칭연산자. 오른쪽을 평가해서 그 결과를 왼쪽에 있는 패턴과 매치하라는 뜻.
  • 18. 왜 단일 할당이 프로그램을 더 낫게 만드는가? 변수의 값을 바꿀수 있다? 누가 언제 바꿨는지 깔끔하게 알기힘듬. 복잡한 잠금 매커니즘 필요. 변수의 값을 바꿀수 없다? 불변상태의 메모리는 read 만 가능. 잠금 매커니즘이필요없다. 즉 쉬운 병행 프로그래밍 가능 어떻게? 프로세스 메시지 전달 방식으로.
  • 19. Pure message passing language 순수 메시지 전달 언어 명령어 3개로병행프로그래밍 가능 spawn : 프로세스 생성 ! (send) : 메시지 보내기 receive : 메시지 받기
  • 20. $ erl 1> Pid = spawn(fun area:loop/0). <0.45.0> 2> Pid! {rect, 6, 10}. rect : 60 3> Pid! {circle, 5}. circle : 78.5 4> Pid! {triangle, 2, 4, 5}. what is it? triangle?
  • 21. area.erl -module(area). -export([loop/0]). loop()-> receive {rect, Width, Ht} -> io:format(“rect : ~p~n”, [Width * Ht]), loop(); {circle, R} -> io:format(“circle : ~p~n”, [3.14 * R * R]), loop(); Other -> io:format(“what is it? ~p?~n”, [Other]), loop() end.
  • 22. Erlang process OS process 와는 다른얼랭자체process 프로세스마다 mailbox 를 하나씩 가짐 프로세스에 메시지를 보내면 mailbox 로 들어가고 receive 문을 평가할때mailbox 에서 메시지를 하나씩 꺼내서 처리
  • 23. 공유메모리 없고 잠금도 필요없으므로Easy 쉬운병행 프로그래밍 가능
  • 24. Erlang? 병행성 멀티코어 분산 무정지
  • 25. 멀티코어 프로그래밍 Multicore programming 쉬운 병행 프로그래밍 덕분에 멀티코어도 역시 쉽게 가능 동일머신의 멀티코어 분산처리 프로세스를 spawn 해서 처리하고 결과모으기
  • 26. -module(pmap). -export([map/2,pmap/2]). map(_, []) -> []; map(F, [H|T]) -> [F(H) | map(F,T)]. pmap(F, L) -> S = self(), Ref = erlang:make_ref(), Pids = map( fun(I) -> spawn(fun() -> do_f(S, Ref, F, I) end) end , L ), gather(Pids, Ref). do_f(Parent, Ref, F, I) -> Parent ! {self(), Ref, (catch F(I))}. gather([Pid|T], Ref) -> receive {Pid, Ref, Ret} -> [Ret|gather(T, Ref)] end; gather([], _) -> [].
  • 27. 싱글코어 프로그래밍 map(_, []) -> []; map(F, [H|T]) -> [F(H) | map(F,T)]. 1> F = fun(X) -> (2 * X) end. #Fun<erl_eval.6.5634564> 2> F(10). 20 3> pmap:map(F,[1,2,3,4,5]). [2,4,6,8,10]
  • 28. 멀티코어 프로그래밍 1> F = fun(X) -> (2 * X) end. #Fun<erl_eval.6.5634564> 2> F(10). 20 3> pmap:pmap(F,[1,2,3,4,5]). [2,4,6,8,10] process 5개가 각각 인수를 병렬로 평가
  • 29. 멀티코어 프로그래밍 pmap(F, L) -> S = self(), Ref = erlang:make_ref(), Pids = map( fun(I) -> spawn(fun() -> do_f(S, Ref, F, I) end) end , L ), gather(Pids, Ref). do_f(Parent, Ref, F, I) -> Parent ! {self(), Ref, (catch F(I))}. gather([Pid|T], Ref) -> receive {Pid, Ref, Ret} -> [Ret|gather(T, Ref)] end; gather([], _) -> [].
  • 30. pmap:pmap(F,[1,2,3,4,5]). Pids = map( fun(I) -> spawn(fun() -> do_f(S, Ref, F, I) end) end , L ), do_f F(I) spawn pmap do_f(Parent, Ref, F, I) -> Parent ! {self(), Ref, (catch F(I))}. Parent ! 2 gather([Pid|T], Ref) -> receive {Pid, Ref, Ret} -> [Ret|gather(T, Ref)] end; gather([], _) -> []. 반복
  • 31. 쉬운 병행프로그래밍 덕분에Easy 쉬운멀티코어 프로그래밍 가능
  • 32. Erlang? 병행성 멀티코어 분산 무정지
  • 33. 분산? Distributed Programming 멀티코어 프로그래밍에서 spawn 으로 생성한 프로세스들이 동일한 머신에 있을필요없음. Erlang node 와 얼랭 표준 라이브러리를 이용
  • 34. 여러머신의 네트워크 분산처리 Erlang node 간의 message 전달방식으로 쉬운분산처리 가능 Erlang node 란 이름을 가지고 있는 Erlang runtime system 이름을 가진 Erlang shell
  • 35. 여러머신의 네트워크 분산처리 server 라는 이름의 Erlang node 실행 $erl –sname server (server@serverhost) 1> 쿠키 각 node 는 쿠키를 한개씩 가지고있고 쿠키가 같은노드끼리만 통신가능 $erl –sname client –setcookieabc (client@clienthost) 1>
  • 36.
  • 37. -module(mod). -export([F/1]). F(X) -> 2*X. $erl –sname server (server@serverhost) 1> rpc:call(client@clienthost, mod, F, [2]). 4 Server Node rpc:call 4 F(2) Client Node $erl –sname client (client@clienthost) 1>
  • 38. Erlang node와 얼랭 표준 라이브러리를 이용하여Easy 쉬운분산 프로그래밍 가능
  • 39. Erlang? 병행성 분산 멀티코어 무정지
  • 40. 무정지? 멈추지 않는 서비스 Server down! 다른서버가 작업을 이어서 수행 무정지는프로세스간의 link 기능으로 쉽게 구현가능
  • 41. Process spawn 내가 생성한 프로세스가 멈춰도 난 모름 Pid = spawn(fun() -> … end) 내가 생성한 프로세스가 멈추면 나도 멈출래 Pid = spawn_link(fun() -> … end) 내가 생성한 프로세스가 멈추면 내가 해결해줄께 process_flag(trap_exit, true), Pid = spawn_link(fun() -> … end)
  • 42. Pid = spawn(fun() -> … end) Pid = spawn_link(fun() -> … end) process_flag(trap_exit, true), Pid = spawn_link(fun() -> … end) A B
  • 43. -module(fault). -export([start/0]). start() -> process_flag(trap_exit, true), spawn_link(fun() -> work() end), loop(). work() -> sleep(5000), 2/0. loop() -> receive {'EXIT',SomePid,Reason} -> io:format("system down !!") end. sleep(T) -> receive after T -> true end.
  • 44. (server@host)1> fault:start(). …5초후… system down !! =ERROR REPORT==== 7-Jan-2009::23:56:29 === Error in process <0.67.0> on node 'server@host' with exit value: {badarith,[{fault,work,0}]} (server@host)2>
  • 45. -module(fault). -export([start/0]). start() -> process_flag(trap_exit, true), spawn_link(fun() -> work() end), loop(). work() -> sleep(5000), 2/0. loop() -> receive {'EXIT',SomePid,Reason} -> io:format("system down !!"), start(). end. sleep(T) -> receive after T -> true end.
  • 46. (server@host)1> fault:start(). …5초후… system down !! =ERROR REPORT==== 7-Jan-2009::23:56:29 === Error in process <0.67.0> on node 'server@host' with exit value: {badarith,[{fault,work,0}]} …5초후… system down !! =ERROR REPORT==== 7-Jan-2009::23:56:34 === Error in process <0.68.0> on node 'server@host' with exit value: {badarith,[{fault,work,0}]}
  • 47. process link 기능을 이용하여Easy 쉬운무정지 프로그래밍 가능
  • 48. Hotcode swapping Dynamic Code Loading 기능 우리가 특정모듈의 특정함수를 호출할때항상 가장 최신 버전의 함수가 호출됨
  • 49. -module(hotcode). -export([start/0]). start() -> spawn(fun() -> loop() end). loop() -> sleep(1000), Val = a:x(), io:format("a:x() : ~p~n", [Val]), loop(). sleep(T) -> receive after T -> true end. -module(a). -export([x/0]). x() -> 1.
  • 50. 1> c(hotcode). {ok,hotcode} 2> hotcode:start(a). <0.49.0> a:x() : 1 a:x() : 1 a:x() : 1 -module(a). -export([x/0]). x() -> 1. -module(a). -export([x/0]). x() -> 2. 3> c(a). {ok,a} a:x() : 2 a:x() : 2
  • 51. 동적 코드 로딩WoW 이런것도 가능
  • 52. Erlang? 애텀, fun, 튜플, 리스트 병행성 공유메모리가 없음 – 잠금필요없음 spawn, ! , receive 3개 명령어 멀티코어 process 여러 개 spawn 해서 처리하고 취합 분산 Erlang node 와 표준 라이브러리 rpc 무정지 process link
  • 53. 언어의 한계가 곧 자기세계의 한계이다. - 루트비히비트켄슈타인
  • 54. reference Programming Erlang –인사이트- http://www.gotw.ca/publications/concurrency-ddj.htm -Herb Sutter- 실용주의프로그래머 –인사이트-