Processing math: 100%

Chenyo's org-static-blog

25 Jun 2024

Go patterns

This a personal note for the Russ Cox guest lecture.

1. Concurrency vs Parallelism

  • Concurrency: write a program to handle lot of things at once
    • not necessarily faster
  • Parallelism: the program itself can do a lot of computations at once

2. Use goroutines for states

2.1. Matching a regex

  • return if a given string matches a regex: start with ", contains arbitrary escape sequence and ends with "
  • unclear logic: store states in the data

  • clear logic: store states in the code

2.2. When the state variable cannot be avoided

  • the function needs to return the state

  • use additional goroutines to hold states

  • check goroutine blockage
    • Ctrl-\ sends SIGQUIT
    • use the HTTP server’s /debug/pprof/goroutine if importing net/http

3. Pattern 1: publish/subscribe server

  • the information goes one way: server -> client
  • close a channel to signal no new values will be sent
  • prefer defer when unlocking the mutex

3.1. Options for slow goroutines

  • slow down event generation
  • drop events if it cannot be sent, e.g., os/signal, runtime/pprof
  • queue events, e.g., add a helper between the server and each client, which also separates the concerns

  • convert mutexes into goroutines, not suitable for Raft where state transition is complex

4. Pattern 2: work scheduler

  • M tasks assigned to N servers/workers, M>>N.

  • Optimization for the above code: while the task loop creates goroutines M times, actually there are only at most N active goroutines at any time.

    • Better to spin off a goroutine for each server.
    • The number of servers can be dynamic.

5. Pattern 3: replicated service client

  • A client replicates its requests to multiple servers, waits for the first reply and changes its preferred server.

6. Pattern 4: Protocol multiplexer

  • A multiplexer sits in front of a service and forward messages between multiple clients and the service, e.g., an RPC.

  • The mux maintains a channel to queue unsent requests and a channel to queue unsent replies.

Tags: go design-pattern study