|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "log" |
| 9 | + "math/big" |
| 10 | + "math/rand" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/ingrammicro/backend-test/queue" |
| 14 | +) |
| 15 | + |
| 16 | +// piComputeData holds both the input and output of a pi processing job |
| 17 | +// Total (both input and output) is the number of random points to pick |
| 18 | +// in a [0,1)x[0,1) square. |
| 19 | +// InCircle (only output) is the number of the randomly picked points that |
| 20 | +// where inside the circle of radius 1 cented in (0,0). |
| 21 | +type piComputeData struct { |
| 22 | + InCircle uint64 `json:"i"` |
| 23 | + Total uint64 `json:"t"` |
| 24 | +} |
| 25 | + |
| 26 | +// piProcessor is a processor that can work out pi processing jobs |
| 27 | +type piProcessor struct{} |
| 28 | + |
| 29 | +// Process processes a pi processing job. To do so, it extracts piComputeData from |
| 30 | +// the given job, computes it and stores it back into the job. It returns an error |
| 31 | +// if any of the three operations fail. |
| 32 | +func (pp piProcessor) Process(ctx context.Context, j queue.JobProcessingAccess) error { |
| 33 | + pcd := &piComputeData{} |
| 34 | + err := j.GetData(pcd) |
| 35 | + if err != nil { |
| 36 | + return err |
| 37 | + } |
| 38 | + err = pcd.Compute(ctx) |
| 39 | + if err != nil { |
| 40 | + return err |
| 41 | + } |
| 42 | + err = j.SetData(ctx, pcd) |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + return nil |
| 47 | +} |
| 48 | + |
| 49 | +// Compute picks a Total number of points in the [0,1)x[0,1) square |
| 50 | +// and checks for each of one if they are inside the circle of radius 1 cented in (0,0). |
| 51 | +// Specifically, given a (x,y) point, it checks whether x²+y² <= 1. |
| 52 | +// It updates InCircle with the number of points that were inside. |
| 53 | +func (pcd *piComputeData) Compute(ctx context.Context) error { |
| 54 | + r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) |
| 55 | + for i := uint64(0); i < pcd.Total; i++ { |
| 56 | + x, y := r.Float64(), r.Float64() |
| 57 | + if (x*x)+(y*y) <= 1 { |
| 58 | + pcd.InCircle++ |
| 59 | + } |
| 60 | + } |
| 61 | + return nil |
| 62 | +} |
| 63 | + |
| 64 | +func (pcd *piComputeData) String() string { |
| 65 | + return fmt.Sprintf("%d/%d", pcd.InCircle, pcd.Total) |
| 66 | +} |
| 67 | + |
| 68 | +// Marshal encodes the piComputeData into the returned byte slice |
| 69 | +// as JSON. |
| 70 | +func (pcd *piComputeData) Marshal() ([]byte, error) { |
| 71 | + buf := &bytes.Buffer{} |
| 72 | + err := json.NewEncoder(buf).Encode(pcd) |
| 73 | + if err != nil { |
| 74 | + return nil, err |
| 75 | + } |
| 76 | + return buf.Bytes(), nil |
| 77 | +} |
| 78 | + |
| 79 | +// Unmarshal decodes the JSON in the given byte slice |
| 80 | +// and fills the piComputeData with it. |
| 81 | +func (pcd *piComputeData) Unmarshal(b []byte) error { |
| 82 | + return json.NewDecoder(bytes.NewReader(b)).Decode(pcd) |
| 83 | +} |
| 84 | + |
| 85 | +// main pushes numberOfJobs pi processing jobs (each computing a million points), |
| 86 | +// starts 10 workers, waits for all the jobs to be processed and then aggregates |
| 87 | +// the results of the jobs to approximate pi. Finally, it prints the approximation |
| 88 | +// and exits orderly. |
| 89 | +func main() { |
| 90 | + const numberOfJobs = 10000 |
| 91 | + ctx, cancelCtx := context.WithCancel(context.Background()) |
| 92 | + defer cancelCtx() |
| 93 | + client, worker := queue.New(piProcessor{}) |
| 94 | + log.Printf("Pushing %d pi processing jobs...", numberOfJobs) |
| 95 | + for i := 0; i < numberOfJobs; i++ { |
| 96 | + client.CreateJob(ctx, fmt.Sprintf("j-%d", i), &piComputeData{Total: 1000000}) |
| 97 | + } |
| 98 | + log.Print("Starting 10 workers...") |
| 99 | + workerStopped := make(chan struct{}) |
| 100 | + go func() { |
| 101 | + worker.Run(ctx, 10) |
| 102 | + close(workerStopped) |
| 103 | + }() |
| 104 | + log.Print("Waiting for results and aggregating them...") |
| 105 | + result := &big.Rat{} |
| 106 | + for i := 0; i < numberOfJobs; i++ { |
| 107 | + jobID := fmt.Sprintf("j-%d", i) |
| 108 | + for { |
| 109 | + job, err := client.GetJob(ctx, jobID) |
| 110 | + if err != nil { |
| 111 | + log.Fatal(err) |
| 112 | + } |
| 113 | + if job == nil { |
| 114 | + log.Fatalf("Job %q could not be found", jobID) |
| 115 | + } |
| 116 | + state := job.State() |
| 117 | + if state == queue.Failed { |
| 118 | + log.Fatal(job.Error()) |
| 119 | + } |
| 120 | + if state == queue.Finished { |
| 121 | + var partialResult piComputeData |
| 122 | + err = job.GetData(&partialResult) |
| 123 | + if err != nil { |
| 124 | + log.Fatal(err) |
| 125 | + } |
| 126 | + result = result.Add(result, big.NewRat(4*int64(partialResult.InCircle), int64(partialResult.Total))) |
| 127 | + break |
| 128 | + } |
| 129 | + time.Sleep(5 * time.Second) // Wait a bit for the job to finish |
| 130 | + } |
| 131 | + } |
| 132 | + cancelCtx() |
| 133 | + result = result.Mul(result, big.NewRat(1, numberOfJobs)) |
| 134 | + log.Printf("Result is %+v = %s", result, result.FloatString(20)) |
| 135 | + log.Printf("Preparing to exit...") |
| 136 | + <-workerStopped |
| 137 | + log.Printf("Exiting") |
| 138 | +} |
0 commit comments