SlideShare uma empresa Scribd logo
1 de 11
Tratamento de Exceções na
Linguagem Go
Aluna:
Karla Polyana Silva Falcão
kpsf@cin.ufpe.br
Orientador:
Fernando J. Castor de Lima Filho
castor@cin.ufpe.br
Universidade Federal
de
Pernambuco
(UFPE)
Centro de Informática
(CIn)
Programação Concorrente
Programa Seqüencial em Go:
package main
import ("time";"fmt")
func a(msg string, sec int64){
time.Sleep(sec *1e9)
fmt.Println(msg)
}
func main(){
fmt.Println("Inicio...")
a("tea", 3)
a("coffee", 2)
time.Sleep(4e9)
fmt.Println("Fim...")
}
Programa Concorrente em Go:
package main
import ("time";"fmt")
func a(msg string, sec int64) {
time.Sleep(sec *1e9)
fmt.Println(msg)
}
func main(){
fmt.Println("Inicio...")
go a("tea", 3)
go a("coffee", 2)
time.Sleep(4e9)
fmt.Println("Fim...")
}
Problemas com Concorrência
#include <pthread.h>
#include <stdio.h>
int x=0;
void *f(void *threadid){
x++;
pthread_exit(NULL);
}
void *g(void *threadid){
x--;
pthread_exit(NULL);
}
int main (){
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, f, NULL);
pthread_create(&thread2, NULL, g, NULL);
printf("%dn",x);
pthread_exit(NULL);
}
 Linguagem C
Problema :
Indeterminismo
- Qual o valor final de “x”?
Solução :
Uso de semáforos, mutexes,
monitores, etc.
Concorrência em Go
package main
import ("fmt")
var x int = 0
var c = make(chan int)
func main(){
go f()
go g()
fmt.Println(<-c)
}
func f() {
x++
c<-x
}
func g() {
x--
c<-x
}
 Facilidade na criação de threads
(goroutines)
 Sincronização
 Sem dados compartilhados entre
threads (goroutines)
 Linguagem Go
Por que Go?
Go é uma linguagem de programação
criada pela Google em setembro de
2009. Já em 2010 alcançou a décima
sexta posição, no ranking da TIOBE
Programming Community.
Go tem foco na facilidade de
programação, desempenho e
escalabilidade em ambiente multi-core,
como é o mundo hoje em dia.
Tratando Erros em Go
(Erros = Exceções)
package main
import ("fmt")
func f(){
div := 9/0
}
func main() {
f()
}
FONTE: http://images.sodahead.com/polls/000628299/polls_panic_attack_5656_707107_answer_5_xlarge.jpeg
package main
import ("fmt")
func f(){
div := 9/0
}
func main() {
defer func(){
if x:=recover();x!=nil{
fmt.Println(“Erro :”,x)
}
fmt.Println(“Tudo Ok!”)
}()
f()
}
go f()
Tratando Erros em Go
(Erros = Exceções)
FONTE: http://images.sodahead.com/polls/000628299/polls_panic_attack_5656_707107_answer_5_xlarge.jpeg
Problema (1)
package main
import ("fmt")
func main() {
defer func(){
if x:=recover();x!=nil{
fmt.Println(“Erro :”,x)
}
fmt.Println(“Tudo Ok!”)
}()
go f()
go g() //Pode entrar em pânico!
go h() //Pode entrar em pânico!
}
 Se houver um erro não recuperado em uma
goroutine todas as outras no mesmo nível e
em níveis superiores morrem!
FONTE: http://kynas.blogs.sapo.pt/arquivo/2004_02.html
Problema (2)
package main
import ("fmt")
var c = make(chan int)
func f(){
time.sleep(3*1e9)
c<-x
}
func main() {
defer func(){
if x:=recover();x!=nil{
fmt.Println(“Erro :”,x)
}
fmt.Println(“Tudo Ok!”)
}()
go f()
<-c
}
FONTE: http://kynas.blogs.sapo.pt/arquivo/2004_02.html
 Não há sincronização implícita entre as
goroutines!
Resolvendo o problema
package main
import ("fmt")
var c = make(chan int)
func f(){
div := 9/0
}
safunc main() {
defer func(){
if x:=recover();x!=nil{
fmt.Println(“Erro :”,x)
}
fmt.Println(“Tudo Ok!”)
}()
go f()
<-c
}
go func(){
if x:=recover();x!=nil{
fmt.Println(“Erro :”,x)
}
fmt.Println(“Tudo Ok!”)
f()
c<-1
}()
Modificação no front-end GCCGO
 Nova palavra reservada
- safunc ( Safe Function)
 Injeção de Código
- Função anônima com tratador
- Canal para a sincronização
http://kynas.blogs.sapo.pt/arquivo/2004_02.html
Referências e agradecimentos
Agradecimentos :
 À FACEPE e ao CNPq pelo financiamento da
pesquisa.
 Ao meu orientador.
Referências :
 Especificação da linguagem Go. End.:
www.golang.org.
 Comunidade que indica a popularidade de
linguagens de programação. End.:
http://www.tiobe.com/index.php/content/paperinf
o/tpci/index.html.

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Tratamento de exceções em GO

  • 1. Tratamento de Exceções na Linguagem Go Aluna: Karla Polyana Silva Falcão kpsf@cin.ufpe.br Orientador: Fernando J. Castor de Lima Filho castor@cin.ufpe.br Universidade Federal de Pernambuco (UFPE) Centro de Informática (CIn)
  • 2. Programação Concorrente Programa Seqüencial em Go: package main import ("time";"fmt") func a(msg string, sec int64){ time.Sleep(sec *1e9) fmt.Println(msg) } func main(){ fmt.Println("Inicio...") a("tea", 3) a("coffee", 2) time.Sleep(4e9) fmt.Println("Fim...") } Programa Concorrente em Go: package main import ("time";"fmt") func a(msg string, sec int64) { time.Sleep(sec *1e9) fmt.Println(msg) } func main(){ fmt.Println("Inicio...") go a("tea", 3) go a("coffee", 2) time.Sleep(4e9) fmt.Println("Fim...") }
  • 3. Problemas com Concorrência #include <pthread.h> #include <stdio.h> int x=0; void *f(void *threadid){ x++; pthread_exit(NULL); } void *g(void *threadid){ x--; pthread_exit(NULL); } int main (){ pthread_t thread1, thread2; pthread_create(&thread1, NULL, f, NULL); pthread_create(&thread2, NULL, g, NULL); printf("%dn",x); pthread_exit(NULL); }  Linguagem C Problema : Indeterminismo - Qual o valor final de “x”? Solução : Uso de semáforos, mutexes, monitores, etc.
  • 4. Concorrência em Go package main import ("fmt") var x int = 0 var c = make(chan int) func main(){ go f() go g() fmt.Println(<-c) } func f() { x++ c<-x } func g() { x-- c<-x }  Facilidade na criação de threads (goroutines)  Sincronização  Sem dados compartilhados entre threads (goroutines)  Linguagem Go
  • 5. Por que Go? Go é uma linguagem de programação criada pela Google em setembro de 2009. Já em 2010 alcançou a décima sexta posição, no ranking da TIOBE Programming Community. Go tem foco na facilidade de programação, desempenho e escalabilidade em ambiente multi-core, como é o mundo hoje em dia.
  • 6. Tratando Erros em Go (Erros = Exceções) package main import ("fmt") func f(){ div := 9/0 } func main() { f() } FONTE: http://images.sodahead.com/polls/000628299/polls_panic_attack_5656_707107_answer_5_xlarge.jpeg
  • 7. package main import ("fmt") func f(){ div := 9/0 } func main() { defer func(){ if x:=recover();x!=nil{ fmt.Println(“Erro :”,x) } fmt.Println(“Tudo Ok!”) }() f() } go f() Tratando Erros em Go (Erros = Exceções) FONTE: http://images.sodahead.com/polls/000628299/polls_panic_attack_5656_707107_answer_5_xlarge.jpeg
  • 8. Problema (1) package main import ("fmt") func main() { defer func(){ if x:=recover();x!=nil{ fmt.Println(“Erro :”,x) } fmt.Println(“Tudo Ok!”) }() go f() go g() //Pode entrar em pânico! go h() //Pode entrar em pânico! }  Se houver um erro não recuperado em uma goroutine todas as outras no mesmo nível e em níveis superiores morrem! FONTE: http://kynas.blogs.sapo.pt/arquivo/2004_02.html
  • 9. Problema (2) package main import ("fmt") var c = make(chan int) func f(){ time.sleep(3*1e9) c<-x } func main() { defer func(){ if x:=recover();x!=nil{ fmt.Println(“Erro :”,x) } fmt.Println(“Tudo Ok!”) }() go f() <-c } FONTE: http://kynas.blogs.sapo.pt/arquivo/2004_02.html  Não há sincronização implícita entre as goroutines!
  • 10. Resolvendo o problema package main import ("fmt") var c = make(chan int) func f(){ div := 9/0 } safunc main() { defer func(){ if x:=recover();x!=nil{ fmt.Println(“Erro :”,x) } fmt.Println(“Tudo Ok!”) }() go f() <-c } go func(){ if x:=recover();x!=nil{ fmt.Println(“Erro :”,x) } fmt.Println(“Tudo Ok!”) f() c<-1 }() Modificação no front-end GCCGO  Nova palavra reservada - safunc ( Safe Function)  Injeção de Código - Função anônima com tratador - Canal para a sincronização http://kynas.blogs.sapo.pt/arquivo/2004_02.html
  • 11. Referências e agradecimentos Agradecimentos :  À FACEPE e ao CNPq pelo financiamento da pesquisa.  Ao meu orientador. Referências :  Especificação da linguagem Go. End.: www.golang.org.  Comunidade que indica a popularidade de linguagens de programação. End.: http://www.tiobe.com/index.php/content/paperinf o/tpci/index.html.