40

Using the Producer-Consumer concurrency pattern in Go. – tpaschalis – physics, s...

 5 years ago
source link: https://tpaschalis.github.io/golang-producer-consumer/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
IntroI’ve been writing new solutions to existing problems using Go.CS50 exercise sets, or psets are interesting little problems, and while the problems themselves are not huge challenges, they’re fun to solve, using a language’s special features to provide idiomatic and efficient solutions.One of the problems was ‘breaking’ a DES hash, to ‘decode’ a 5-character password. The bruteforce approach is quite slow, but using simple concurrency, there was a 5x speedup, without adding much complexity. Here’s the solution in a gist. If you have any suggestions for improvements, you can leave a comment or feel free to fork it.The Pattern in GoThis specific problem was a good opportunity to implement a “Producer-Consumer” pattern.Being familiar with OpenMP's idea of parallel computing, I had an overview of the various common pitfalls, and how to overcome them (resource sharing is hard, man). Go provides a much simpler interface to deal with them, and forces you into a different mindset, eg. Do not communicate by sharing memory; instead, share memory by communicating.Without sacrificing too many details, here’s an outline of how I implemented the “Producer-Consumer” on this casefunc produce(in chan string) { defer close(in) // producedPassword = somestuff.... in <- producedPassword}func consume(in, out chan string, wg *sync.WaitGroup) { defer wg.Done() for s := range in { currentHash := crypt(s) // success condition if currentHash == hashToCrack { fmt.Println(currentHash,

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK