Answer the question
In order to leave comments, you need to log in
Why is goroutine not doing its job?
After reading the theory of how goroutines work, in principle, nothing is difficult, I solve a practical problem to understand them, but I ran into a problem, I would like to get advice on a live example, rather than in the output "Hello wordl!" goroutines in a loop.
package main
import (
"bufio"
"bytes"
"fmt"
"golang.org/x/crypto/bcrypt"
"io"
"os"
"strings"
"sync"
)
var (
hash_target = "$2y$10$Jk2gOsrCgYKaVutj9JIVYuXlinrpzeqxdXng/Nm96O7t5AvVBir/a"
dict = "/home/supreme/rockyou.txt"
r io.Reader
err error
)
func main(){
r, err := os.Open(dict)
if err != nil{
fmt.Println(err)
}
defer r.Close()
var wg sync.WaitGroup
var reader *bufio.Reader = bufio.NewReader(r)
var pasw string
wg.Add(1)
for {
pasw, err = reader.ReadString('\n')
if err == io.EOF {
fmt.Printf("File %s end detected", dict)
} else {
pasw = strings.Replace(pasw, "\n", "", -1)
go hack_pass(pasw, hash_target, &wg)
}
}
wg.Wait()
}
func hack_pass(str string,hash_target string, wg *sync.WaitGroup){
fmt.Println("----------------------------------")
if CheckPasswordHash(str,hash_target){
fmt.Println("----------------------------------")
fmt.Println("[SUCCESS]:", str)
fmt.Println("----------------------------------")
os.Exit(0)
}else{
fmt.Println("[FAILURE]:", str)
}
wg.Done()
return
}
func CheckPasswordHash(password string, hash string)bool{
err := bcrypt.CompareHashAndPassword([]byte(hash),[]byte(password))
return err == nil
}
Answer the question
In order to leave comments, you need to log in
You add a unit to wg, the first executing goroutine subtracts this unit, wg.Wait() unblocks the thread and main ends. wg.Add needs to be done for every goroutine you want to wait
. Also os.Exit ends the whole process. That is, the first goroutine that stumbles upon it will end everything
. Still, you are absolutely uncontrollably spawning goroutines in an endless loop. Use an adequate number of goroutines that work at the same time and throw them tasks through channels Read the
theory a couple more times Here is another great article
that will help
you understand goroutines and typical examples of their use
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question