Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make TaskManager safe for concurrent access #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Make TaskManager safe for concurrent access
nerdatmath committed Nov 27, 2014
commit 4d3ba9895de407ba6795943cd43f4e92750ca702
16 changes: 14 additions & 2 deletions task/task.go
Original file line number Diff line number Diff line change
@@ -15,7 +15,10 @@
// The tests were developed before the code was written.
package task

import "fmt"
import (
"fmt"
"sync"
)

type Task struct {
ID int64 // Unique identifier
@@ -33,6 +36,7 @@ func NewTask(title string) (*Task, error) {

// TaskManager manages a list of tasks in memory.
type TaskManager struct {
sync.RWMutex
tasks []*Task
lastID int64
}
@@ -44,6 +48,8 @@ func NewTaskManager() *TaskManager {

// Save saves the given Task in the TaskManager.
func (m *TaskManager) Save(task *Task) error {
m.Lock()
defer m.Unlock()
if task.ID == 0 {
m.lastID++
task.ID = m.lastID
@@ -68,12 +74,18 @@ func cloneTask(t *Task) *Task {

// All returns the list of all the Tasks in the TaskManager.
func (m *TaskManager) All() []*Task {
return m.tasks
m.RLock()
defer m.RUnlock()
out := make([]*Task, len(m.tasks))
copy(out, m.tasks)
return out
}

// Find returns the Task with the given id in the TaskManager and a boolean
// indicating if the id was found.
func (m *TaskManager) Find(ID int64) (*Task, bool) {
m.RLock()
defer m.RUnlock()
for _, t := range m.tasks {
if t.ID == ID {
return t, true