package main // A system in Go to limit the number of running threads // This behaves a lot like the Java FixedThreadPool Executor // The idea is to create an instance of a slice that holds instruction // for each "thread run". // Then start the number of threads you want. // Each thread reads the instructions for a thread run from the slice and // does that work. Then it reads another instruction and does that. // Until there are no more instructions. At which point the // thread dies // // This approach has the problem that the counter in the slice could // be incremented by two different threads. // // This version differs from the non-B in that it uses a slice as // shared memory holding thread instructions rather than a // message passing channel. Hence, this version is pure // shared memory rather than an odd mix of message and shared. import ( "fmt" "sync" ) const xthreads = 3 // Total number of threads to use, excluding the main() thread const times = 1000000 // the amount of counting to do const reps = 5 // the number of times to count. // the shared memory where all the work is done var counter int64 // a struct to hold thread instructions type instruct struct { lowNum int highNum int } // the slice holding all of the instructions var instructions []instruct // next instruction to be read on a thread var currentInstruction int // a stupid function to do some work in a thread func doSomething(lowNum int, highNum int) { for th:=lowNum; th=len(instructions) { break; } ins := instructions[currentInstruction] fmt.Printf("Thread %v message: %v\n", threadCounter, currentInstruction) doSomething(ins.lowNum, ins.highNum) // do the thing } }(i) } wg.Wait() // Wait for the threads to finish fmt.Printf("Reps: %v Count:%v\n", reps, times) fmt.Printf("Total count %v shortfall:%v\n", counter, (int64((times*reps))-counter)) }