package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"sync"
)
func calculateMD5(filePath string, sema chan struct{}, wg *sync.WaitGroup, results chan<- string) {
defer wg.Done()
sema <- struct{}{}
defer func() { <-sema }()
file, err := os.Open(filePath)
if err != nil {
results <- fmt.Sprintf("Ошибка открытия %s: %v", filePath, err)
return
}
defer file.Close()
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
results <- fmt.Sprintf("Ошибка чтения %s: %v", filePath, err)
return
}
hashInBytes := hash.Sum(nil)
hashString := hex.EncodeToString(hashInBytes)
results <- fmt.Sprintf("Файл: %s | MD5: %s", filepath.Base(filePath), hashString)
}
func main() {
files := []string{"test1.txt", "test2.txt", "test3.txt"}
for _, name := range files {
os.WriteFile(name, []byte("содержимое файла "+name), 0644)
defer os.Remove(name)
}
var wg sync.WaitGroup
sema := make(chan struct{}, 2)
results := make(chan string, len(files))
for _, file := range files {
wg.Add(1)
go calculateMD5(file, sema, &wg, results)
}
wg.Wait()
close(results)
for res := range results {
fmt.Println(res)
}
}