6407
31 flashcards · Programming Languages · by brokeyourbike
What this program will print? func main() { runtime.GOMAXPROCS(1) done := false go func() { done = true }() for !done { } fmt.Println("finished") }
For me it's printing finished But on the golang playground it will timeout, maybe because they give only 1 core to the server and it cannot run the goroutine?
What should be changed to print finished ? func main() { runtime.GOMAXPROCS(1) done := false go func() { done = true }() for !done { } fmt.Println("finished") }
use GOMAXPROCS value more then 1 on single core machine?
Как устроены каналы “под капотом”?
it's a struct hchan which has receive and wait linked lists and a mutex
What is the problem with this code? How to solve it? var counter int for i := 0; i < 1000; i++ { go func() { counter++ }() }
use sync.WaitGroup to synchronize goroutines and use sync.Mutex to ensure only one goroutine will write to the variable at a time wg := sync.WaitGroup{} wg.Add(1000) m := sync.Mutex{} var counter int for i := 0; i < 1000; i++ { go func() { m.Lock() counter++ m.Unlock() wg.Done() }() } wg.Wait()
What this code will print? Why? func main() { v := 5 p := &v println(*p) changePointer(p) println(*p) } func changePointer(p *int) { v := 3 p = &v }
5 5
This code will print 5 5. How to make it display 5 3 ? func main() { v := 5 p := &v println(*p) changePointer(p) println(*p) } func changePointer(p *int) { v := 3 p = &v }
func changePointer(p *int) { v := 3 *p = v }
How long it will take to run the program 3 or 6 seconds? Why? func worker() chan int { ch := make(chan int) go func() { time.Sleep(3 * time.Second) ch <- 42 }() return ch } func main() { timeStart := time.Now() _, _ = <-worker(), <-worker() println(int(time.Since(timeStart).Seconds())) // что выведет - 3 или 6? }
6 reading from channel is a blocking opperation we run 2 separate goroutines and wait for data from the channel that's why we have to wait till both of them receive something
This program will take 6 seconds to run, how can we make it run in 3? func worker() chan int { ch := make(chan int) go func() { time.Sleep(3 * time.Second) ch <- 42 }() return ch } func main() { timeStart := time.Now() _, _ = <-worker(), <-worker() println(int(time.Since(timeStart).Seconds())) }
We should not create 2 separate channels Create one channel and read 2 times from it
What happend when we write to the buffered chan ?
mutex lock copy passed value to the buffer mutex unlock
What happend when we read from the buffered chan ?
mutex lock copy passed value value removed from buffer mutex unlock
What happend when goroutine tries to write to the chan with full buffer?
sudog struct created for goroutine writing goroutine state changed to waiting struct added to the waitq linked list when buffer can be written to again: sudog struct extracted from waitq data copied to the buffer goroutine state become runnable
What happend when you read form the chan with empty buffer?
new sudog structure creted for goroutine (sudog structure holds a memory address which will be used when other goroutine will write some data) goroutine state become waiting this structure added to the linked list recv when other goroutine will write some data, they will be passes directly to the reading goroutine reading goroutine state become runnable
How unbuffered chan looks like unders the hood?
buf will be empty
What happend when we write to unbuffered chan under the hood?
searching for reading goroutine in recv removes goroutine from recv writes directly to the goroutine
What happend when you close a chan under the hood?
checking if chan initialized locking mutex checking if chan is closed value of closed field in the hchan struct set to true all structs waiting to be read receive default values all structs waiting to be written receive panic unloking mutex blokced goroutines unlocked
What this code will show? f := 500.0 fmt.Printf("float: %v\n", f/0)
float: +Inf
What this code will show? x := 100.0 fmt.Printf("%v\n", x/0)
invalid operation: division by zero
How defer called? func main() { defer fmt.Println(1) defer fmt.Println(2) fmt.Println("done") }
done 2 1 defer called in reverse order, using FIFO
What this code will print? x := 1 defer fmt.Println(x) x = 2
1 values passed to defer evaluated imidiately
What are the benefits of container orchestration?
simplified operation (no need humans to operate) resilience (tools can auto restart failed ones) security (less human errors)
What are containers?
Containers are a method of building, packaging and deploying software.
What are the benefits of containers?
portability (built to run in any environment) application development (if we use microservices, we can update small pieces independently) resource optimization (they are light, and multiple of them can be run on single machine)
What is multi-cloud container orchestration?
it's an IT strategy of using 2 or more cloud providers
12 factor apps?
codebase tracked declare and isolate dependencies store config in the environment treas services (DB, cache) like attached separate build and run stages app = stateless process export services with port binding scale out with process model gracefull shutdown, fast startup dev and prod environment should be as similar as possible logs are event streams run admin scripts as one-off process
How to implement stack ?
type Stack []int func (s Stack) Empty() bool { return len(s) == 0 } func (s *Stack) Push(v int) { (*s) = append((*s), v) } func (s *Stack) Pop() int { v := (*s)[len(*s)-1] (*s) = (*s)[:len(*s)-1] return v }
How to implement queue ?
type Queue []int func (q Queue) Empty() bool { return len(q) == 0 } func (q *Queue) Enqueue(v int) { (*q) = append((*q), v) } func (q *Queue) Dequeue() int { v := (*q)[0] (*q) = (*q)[1:len(*q)] return v }
How to traverse a linked list?
if node != nil { fmt.Println(node.Value) node = node.Next }
How to implement stack with linked list ?
type n struct { Data string Next *n } type stack struct { length int head *n } func (s *stack) Push(v string) { s.head = &n{Data: v, Next: s.head} s.length++ } func (s *stack) Pop() (string, error) { if s.head != nil { v := s.head.Data s.head = s.head.Next s.length-- return v, nil } return "", errors.New("no items") }
What this code will print? s1 := []int{1, 2, 3} s2 := []int{0} copy(s2, s1) fmt.Println(s2)
1 we are copying from dst to src copy(dst, src)
Define SOLID
S - single responsibility class should have only one reason to change structure functions, types and methods into packages O - open / closed principle open for extension, closed for modification composite simple structs into complex ones L - Liskov substitution express dependencies as interfaces I - interface segregation do not depend on methods you don't use define functions and methods that depend only on what they need (using small interfaces like: io.Reader) D - dependency inversion abstrac…
What are the pillars of OOP?
Encapsulation - public/private methods Abstraction - use of interfaces Inheritance - class can inherit other class (not in Go) Polymorphism - child class can do the same as parent