package main
import (
"fmt"
"time"
)
const (
total = 100
)
//Printer1
func Printer1(a, b chan int) {
for i := range a {
if i > 100 {
return
}
fmt.Printf("Printer1--%d\r\n", i)
b <- i + 1
}
}
func Printer2(a, b chan int) {
for i := range a {
if i > 100 {
return
}
fmt.Printf("Printer2--%d\r\n", i)
b <- i + 1
}
}
func main() {
a := make(chan int)
b := make(chan int)
go Printer1(a, b)
go Printer2(b, a)
a <- 0
time.Sleep(time.Millisecond * 10) //阻塞
close(a)
close(b)
fmt.Printf("exit\n")
}
2)
package main
import (
"bufio"
"fmt"
"io"
"os"
"sort"
"strings"
)
const (
LOG = "/Users/jinhailang/Desktop/test.txt" //"/home/admin/logs/data.log"
)
func cat(path, key string) ([]string, error) {
var ss []string
fi, err := os.Open(LOG)
if err != nil {
fmt.Printf("Open error: %v\n", err)
return nil, err
}
defer fi.Close()
br := bufio.NewReader(fi)
for {
a, _, c := br.ReadLine()
if c == io.EOF {
break
}
s := string(a)
if strings.Contains(s, key) {
ss = append(ss, s)
}
}
fmt.Println("ss: ", ss)
return ss, nil
}
func uniq(ss []string) map[string]int {
mp := make(map[string]int)
for _, s := range ss {
count, ok := mp[s]
if ok {
count++
mp[s] = count
} else {
mp[s] = 1
}
}
return mp
}
type kv struct {
K string
V int
}
type kvs []kv
func (p kvs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p kvs) Len() int { return len(p) }
func (p kvs) Less(i, j int) bool { return p[i].V < p[j].V }
func sort_nr(mp map[string]int) []kv {
p := make(kvs, len(mp))
i := 0
for k, v := range mp {
p[i] = kv{k, v}
i = i + 1
}
sort.Sort(p)
return p
}
func main() {
ss, _ := cat(LOG, "alibaba")
sort.Strings(ss)
fmt.Println("sort after ss: ", ss)
mp := uniq(ss)
fmt.Println("uniq after mp: ", mp)
kk := sort_nr(mp)
fmt.Println("sort_nr after kk: ", kk)
fmt.Println("exit.")
}
在线代码测试
1)
2)