Skip to content

Instantly share code, notes, and snippets.

@chavitos
Created January 8, 2020 03:03
Show Gist options
  • Save chavitos/3f6d676ba8eed2562d277aad49a95f55 to your computer and use it in GitHub Desktop.
Save chavitos/3f6d676ba8eed2562d277aad49a95f55 to your computer and use it in GitHub Desktop.
Playground usado no vídeo Problemas na programação concorrente! Caso o arquivo não abra diretamente do xcode (apple sendo apple haha) copie o conteúdo e cole em um playground seu! :D
import UIKit
/*
105 Developers
Problemas que podem ocorrer com a programação concorrente.
*/
/*
Problemas:
- Deadlock (impasse)
- Race condition (condição de corrida)
# Deadlock
Impasse
Um recurso depende de um segundo recurso, porém, esse segundo recurso depende do primeiro. Lascou!
Muito comum quando chamamos uma mesma fila de dentro de uma bloco dessa mesma fila
# Race condition
Condição de corrida
Quando + de 1 thread tenta utilizar o mesmo recurso ao mesmo tempo
Exemplo: Um objeto count com valor 1 vai ser incrementado em 1 (count += 1) por 2 threads:
Valor 1 1 2 2 X
Thread1 r1 +1 w2
Thread2 r1 +1 w2 ------> valor escrito deveria ser 3 mas a condição de corrida ocorreu
==============Tempo=================
*/
// HANDS ON!
// Deadlock
//let q = DispatchQueue(label: "myQueue")
//
//q.async {
// print("work async start")
// q.async {
// print("work sync in async (tiltei :p)")
// }
// print("work async end")
//}
//
//print("Done")
// Race Condition
//class RaceCondition {
//
// var array:[String] = []
// let concurrentQueue = DispatchQueue(label: "concurrent", attributes: .concurrent)
//
// func load() {
// concurrentQueue.async(flags: .barrier) {
// for i in 0...300 {
// usleep(3)
// self.array.append("🌎: \(i)")
// }
// self.printArray()
// }
//
// concurrentQueue.async(flags: .barrier) {
// for i in 0...300 {
// self.array[i] = "⚽: \(i)"
// }
//
// self.printArray()
// }
// }
//
// func printArray() {
// array.forEach { item in
// print(item)
// }
// }
//}
//
//let error = RaceCondition()
//error.load()
private let threadSafeCountQueue = DispatchQueue(label: "...")
private var _count = 0
public var count: Int {
get {
return threadSafeCountQueue.sync {
_count
}
}
set {
threadSafeCountQueue.sync { _count = newValue }
}
}
private let threadSafeCountQueue2 = DispatchQueue(label: "...", attributes: .concurrent)
private var _count2 = 0
public var count2: Int {
get {
return threadSafeCountQueue2.sync {
return _count2
}
}
set {
threadSafeCountQueue2.async(flags: .barrier) {
_count2 = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment