[ASK] Multithreaded Generate Character

Hi guys,

I just learn Golang this week. I learn Golang by creating a simple personal case to make it easier to learn.
I saw this thread and I got an idea to build a md5 cracker.

I tried this code but it doesnt work like I want. what did I missed and how to separate the process efficiently to make it faster?

runtime.GOMAXPROCS(2)
var wg sync.WaitGroup

for combination := range GenerateCombinations(alpha, length) {
wg.Add(2)
go func() {
defer wg.Done()
if hash == GetMD5Hash(combination) {
fmt.Println(“hash → " + combination)
//return true
}
}()//fmt.Println(”—=== " + combination + " ===—“)
go func() {
defer wg.Done()
if hash == GetMD5Hash(combination) {
fmt.Println(“hash → " + combination)
//return true
}
}()//fmt.Println(”—=== " + combination + " ===—”)

Thanks in advance.

Regards

Difficult to say what is wrong with the code. A bit more context would certainly help; for example,

  • In what way does the code fail? Can you provide an example of expected vs observed result?

  • How does the rest oft the code look like? (Maybe the issue is caused by something outside the snippet you posted.)

I want to separate the process by the first letter. for example:

a to aaaaaa = run in process 1
b to bbbbbb = run in process 2
c to cccccc = run in process 3
etc

Sorry, I was not on my PC right now, but I will post it later ASAP.
I’m using time.Now and time.Since to benchmark the process with/without multithreaded and the result for multithreaded was longer than single process.

Hey @dummy,

Not exactly sure what you are trying to do here, but from the sounds of it, you might be looking for something like this:

package main

import (
	"crypto/md5"
	"fmt"
)

func worker(in, out chan string, done chan struct{}, i int) {
	for {
		select {
		case <-done:
			return
		case str := <-in:
			// Send the hash of str and the current goroutine worker
			// number on the out channel.
			out <- fmt.Sprintf("%d: %x", i, md5.Sum([]byte(str)))
		}
	}
}

func main() {
	in, out := make(chan string), make(chan string)
	done := make(chan struct{})

	// Start 25 worker goroutines.
	for i := 0; i < 25; i++ {
		go worker(in, out, done, i)
	}

	// Send the data on the in channel.
	go func() {
		for i := 0; i < 10; i++ {
			in <- fmt.Sprintf("Hello, %d", i)
		}
	}()

	// Receive the data from the out channel.
	for i := 0; i < 10; i++ {
		fmt.Println(<-out)
	}

	// Close done so all of the worker goroutines exit and
	// no goroutines are leaked.
	close(done)
}

Either way, you should read this blog: https://blog.golang.org/pipelines.

Hi @radovskyb,

I will try to use in and out channel to solve my problem. Thanks for pointing me to that blog. :slight_smile:

No problem :smiley: I remember it being a good read. Enjoy!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.