huaweicloud-iot-device-sdk-go/async.go

113 lines
1.8 KiB
Go
Raw Normal View History

2021-03-25 23:37:30 +08:00
package iot
import (
"sync"
"time"
)
2021-04-19 23:36:23 +08:00
type DeviceError struct {
errorMsg string
}
func (err *DeviceError) Error() string {
return err.errorMsg
}
2021-03-25 23:37:30 +08:00
type AsyncResult interface {
Wait() bool
WaitTimeout(time.Duration) bool
Done() <-chan struct{}
Error() error
}
type baseAsyncResult struct {
m sync.RWMutex
complete chan struct{}
err error
}
// Wait implements the Token Wait method.
func (b *baseAsyncResult) Wait() bool {
<-b.complete
return true
}
// WaitTimeout implements the Token WaitTimeout method.
func (b *baseAsyncResult) WaitTimeout(d time.Duration) bool {
timer := time.NewTimer(d)
select {
case <-b.complete:
if !timer.Stop() {
<-timer.C
}
return true
case <-timer.C:
}
return false
}
// Done implements the Token Done method.
func (b *baseAsyncResult) Done() <-chan struct{} {
return b.complete
}
func (b *baseAsyncResult) flowComplete() {
select {
case <-b.complete:
default:
close(b.complete)
}
}
func (b *baseAsyncResult) Error() error {
b.m.RLock()
defer b.m.RUnlock()
return b.err
}
func (b *baseAsyncResult) setError(e error) {
b.m.Lock()
b.err = e
b.flowComplete()
b.m.Unlock()
}
type BooleanAsyncResult struct {
baseAsyncResult
}
func (bar *BooleanAsyncResult) Result() bool {
bar.m.RLock()
defer bar.m.RUnlock()
2021-03-30 07:59:27 +08:00
return bar.err == nil
2021-03-25 23:37:30 +08:00
}
func (bar *BooleanAsyncResult) completeSuccess() {
2021-03-25 23:37:30 +08:00
bar.m.RLock()
defer bar.m.RUnlock()
bar.err = nil
2021-03-25 23:37:30 +08:00
bar.complete <- struct{}{}
}
func (bar *BooleanAsyncResult) completeError(err error) {
bar.m.RLock()
defer bar.m.RUnlock()
bar.err = err
2021-03-25 23:37:30 +08:00
bar.complete <- struct{}{}
}
func NewBooleanAsyncResult() *BooleanAsyncResult {
asyncResult := &BooleanAsyncResult{
baseAsyncResult: baseAsyncResult{
complete: make(chan struct{}),
},
}
return asyncResult
}