Skip to content

Crash in simple producer/consumer program #14

@albertolluch

Description

@albertolluch

The program below crashes:

// This is a simple producer/consumer system.

package main

import (
	"fmt"
	"math/rand"
	"time"

	. "github.com/pspaces/gospace"
)

// PRODUCERS defines the number of producers.
const PRODUCERS = 2

// NTASKS defines the number of tasks each producer generates.
const NTASKS = 2

// WORKERS defines the number of workers.
const WORKERS = 2

func main() {

	rand.Seed(time.Now().UTC().UnixNano())

	bag := NewSpace("bag")

	for i := 0; i < PRODUCERS; i++ {
		go producer(&bag, i, NTASKS)
	}

	for i := 0; i < WORKERS; i++ {
		go worker(&bag, i)
	}

	bag.Query("done")

}

func producer(bag *Space, me int, ntasks int) {
	for i := 0; i < ntasks; i++ {
		x := rand.Intn(10)
		bag.Put(x)
		fmt.Printf("Producer %d added %d to the bag...\n", me, x)
	}
}

func worker(bag *Space, me int) {
	var x int
	var y int
	for {
		// Get one number.
		bag.Get(&x)
		// Try to get another number.
		_, err := bag.GetP(&y)
		if err == nil {
			// If found then reduce.
			fmt.Printf("Worker %d got pair (%d,%d) to reduce.\n", me, x, y)
			x = x + y
			bag.Put(x)
			fmt.Printf("Worker %d added %d to the bag.\n", me, x)
		} else {
			// If not found, replace the first number.
			bag.Put(x)
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions