twitchapon-anim

Basic Twitchapon Receiver/Visuals
git clone git://bsandro.tech/twitchapon-anim
Log | Files | Refs | README | LICENSE

thread.go (1596B)


      1 // Copyright 2018 The Ebiten Authors
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package thread
     16 
     17 import (
     18 	"errors"
     19 )
     20 
     21 // Thread represents an OS thread.
     22 type Thread struct {
     23 	funcs   chan func() error
     24 	results chan error
     25 }
     26 
     27 // New creates a new thread.
     28 //
     29 // It is assumed that the OS thread is fixed by runtime.LockOSThread when New is called.
     30 func New() *Thread {
     31 	return &Thread{
     32 		funcs:   make(chan func() error),
     33 		results: make(chan error),
     34 	}
     35 }
     36 
     37 // BreakLoop represents an termination of the loop.
     38 var BreakLoop = errors.New("break loop")
     39 
     40 // Loop starts the thread loop until a posted function returns BreakLoop.
     41 //
     42 // Loop must be called on the thread.
     43 func (t *Thread) Loop() {
     44 	for f := range t.funcs {
     45 		err := f()
     46 		if err == BreakLoop {
     47 			t.results <- nil
     48 			return
     49 		}
     50 		t.results <- err
     51 	}
     52 }
     53 
     54 // Call calls f on the thread.
     55 //
     56 // Do not call this from the same thread. This would block forever.
     57 //
     58 // If f returns BreakLoop, Loop returns.
     59 //
     60 // Call blocks if Loop is not called.
     61 func (t *Thread) Call(f func() error) error {
     62 	t.funcs <- f
     63 	return <-t.results
     64 }