github.com/annchain/OG@v0.0.9/tests/lock_test/lock_test.go (about)

     1  // Copyright © 2019 Annchain Authors <EMAIL ADDRESS>
     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  package lock_test
    15  
    16  import (
    17  	"fmt"
    18  	"net/http"
    19  	"sync"
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  func testMain() {
    25  	go func() {
    26  		err := http.ListenAndServe("0.0.0.0:"+"1510", nil)
    27  		if err != nil {
    28  			panic(err)
    29  		}
    30  	}()
    31  	var P = Person{
    32  		Name: "hahah",
    33  		ID:   345,
    34  	}
    35  	var g = Group{}
    36  	g.SetHead(&P)
    37  	fmt.Println("start")
    38  	var q = make(chan bool)
    39  	var num int
    40  	go func() {
    41  		for {
    42  			select {
    43  			case <-time.After(time.Second * 1):
    44  				fmt.Println("hahahh", num)
    45  				num++
    46  				if num > 100 {
    47  					q <- true
    48  					return
    49  				}
    50  			}
    51  		}
    52  	}()
    53  	for {
    54  		select {
    55  		case <-time.After(1 * time.Second):
    56  			go fmt.Println(g.GetHead())
    57  			go fmt.Println(g.GetHeadId())
    58  			go fmt.Println(g.GetHead().ID)
    59  		case <-q:
    60  			fmt.Println("end")
    61  			return
    62  
    63  		}
    64  	}
    65  }
    66  
    67  func TestLocker(t *testing.T) {
    68  	testMain()
    69  
    70  }
    71  
    72  type Person struct {
    73  	Name string
    74  	ID   int
    75  }
    76  
    77  type Group struct {
    78  	Head *Person
    79  	mu   sync.RWMutex
    80  	//
    81  }
    82  
    83  func (g *Group) SetHead(s *Person) {
    84  	g.mu.Lock()
    85  	defer g.mu.Unlock()
    86  	g.Head = s
    87  }
    88  
    89  func (g *Group) GetHead() (s *Person) {
    90  	g.mu.RLock()
    91  	defer g.mu.RUnlock()
    92  	return g.Head
    93  }
    94  
    95  func (g *Group) GetHeadId() (id int) {
    96  	g.mu.RLock()
    97  	defer g.mu.RUnlock()
    98  	return g.Head.ID
    99  }