Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "sync"
- )
- type ILibraryState interface {
- DoSomething(arg int) error
- }
- type LibraryState struct {
- lock *sync.Mutex
- // Some private state
- }
- func (l *LibraryState) DoSomething(arg int) error {
- // Do some arg check
- // Transactional synchronisation
- l.lock.Lock()
- defer l.lock.Unlock()
- // Do something
- fmt.Println("Hello, playground")
- return nil;
- }
- func NewLibrary() ILibraryState {
- lib := LibraryState{}
- lib.lock = &sync.Mutex{}
- return &lib
- }
- func main() {
- l := NewLibrary()
- l.DoSomething(5)
- }
- package main
- import (
- "fmt"
- )
- type ILibraryState interface {
- DoSomething(arg int) error
- }
- type LibraryState struct {
- command chan (interface{})
- response chan (interface{})
- // Some private state
- }
- type commandDoSomething struct {
- arg int
- }
- func (l *LibraryState) DoSomething(arg int) error {
- // Do some arg check
- // Perform operation transactionally
- l.command <- commandDoSomething{arg}
- res := <-l.response
- if res == nil {
- return nil
- }
- return res.(error)
- }
- func (l *LibraryState) reallyDoSomething(arg int) {
- // Do something
- fmt.Println("Hello, playground")
- var err error = nil
- l.response <- err
- }
- func (l *LibraryState) processCommands() {
- for {
- switch c := (<-l.command).(type) {
- case commandDoSomething:
- l.reallyDoSomething(c.arg)
- }
- }
- }
- func NewLibrary() ILibraryState {
- lib := LibraryState{}
- lib.command = make(chan (interface{}))
- lib.response = make(chan (interface{}))
- go lib.processCommands()
- return &lib
- }
- func main() {
- l := NewLibrary()
- l.DoSomething(5)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement