From 1f0fccdacb4550aa8f6cae9345e04f1fcbd5f217 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Fri, 31 Dec 2021 11:33:27 +0800 Subject: [PATCH] add: 211231-CN multi-threaded searching --- 2112/211231-CN.cpp | 87 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) diff --git a/2112/211231-CN.cpp b/2112/211231-CN.cpp index 61d3a85..85c81e2 100644 --- a/2112/211231-CN.cpp +++ b/2112/211231-CN.cpp @@ -28,4 +28,89 @@ int main() { std::printf("%d\n", i); } return 0; -} \ No newline at end of file +} + +/** + * Use this golang program to do multi-threaded searching: + * +package main + +import ( + "fmt" + "math" + "sync" + "time" +) + +type taskArgument struct { + L uint32 + R uint32 +} + +var ( + tasks = make(chan taskArgument) + printContent = make(chan string) +) + +const ( + step = 500000 + limit = 100000000 +) + +func taskExecutor(mutex *sync.Mutex) { + mutex.Lock() + defer mutex.Unlock() + for { + args, ok := <-tasks + if !ok { + return + } + for i := args.L; i <= args.R; i++ { + var s uint32 = 1 + lim := uint32(math.Sqrt(float64(i) + 0.5)) + for j := uint32(2); j <= lim; j++ { + if i%j == 0 { + s += j + i/j + } + } + if s == i { + printContent <- fmt.Sprintf("%d", i) + } + } + printContent <- fmt.Sprintf("Finishing searching [%d, %d]", args.L, args.R) + } +} + +func main() { + go Printer() + threads := 20 + locks := make([]sync.Mutex, threads) + start := time.Now() + for i := 0; i < threads; i++ { + go taskExecutor(&locks[i]) + } + for i := 1; i < limit; i += step { + tasks <- taskArgument{ + L: uint32(i), + R: uint32(i + step - 1), + } + } + close(tasks) + time.Sleep(1 * time.Second) + for i := 0; i < threads; i++ { + locks[i].Lock() + } + end := time.Now() + fmt.Println(end.Sub(start)) +} + +func Printer() { + for { + s, ok := <-printContent + if !ok { + return + } + fmt.Println(s) + } +} + */ \ No newline at end of file