go-channel.go 983 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package common
  2. import (
  3. "fmt"
  4. "runtime/debug"
  5. )
  6. func SafeGoroutine(f func()) {
  7. go func() {
  8. defer func() {
  9. if r := recover(); r != nil {
  10. SysError(fmt.Sprintf("child goroutine panic occured: error: %v, stack: %s", r, string(debug.Stack())))
  11. }
  12. }()
  13. f()
  14. }()
  15. }
  16. func SafeSendBool(ch chan bool, value bool) (closed bool) {
  17. defer func() {
  18. // Recover from panic if one occured. A panic would mean the channel was closed.
  19. if recover() != nil {
  20. closed = true
  21. }
  22. }()
  23. // This will panic if the channel is closed.
  24. ch <- value
  25. // If the code reaches here, then the channel was not closed.
  26. return false
  27. }
  28. func SafeSendString(ch chan string, value string) (closed bool) {
  29. defer func() {
  30. // Recover from panic if one occured. A panic would mean the channel was closed.
  31. if recover() != nil {
  32. closed = true
  33. }
  34. }()
  35. // This will panic if the channel is closed.
  36. ch <- value
  37. // If the code reaches here, then the channel was not closed.
  38. return false
  39. }