Skip to content

Instantly share code, notes, and snippets.

@LukeB42
Last active January 24, 2016 21:08
Show Gist options
  • Save LukeB42/a952bdde229355bd7bc8 to your computer and use it in GitHub Desktop.
Save LukeB42/a952bdde229355bd7bc8 to your computer and use it in GitHub Desktop.
A simple time server for demonstrating a mix of pthreads and goroutines
package main
import (
pthread "github.com/lukeb42/go-pthreads"
"fmt"
"io"
"log"
"net"
"time"
)
func main() {
fmt.Println("Binding to localhost:8000")
thread1 := pthread.Create(spinner, 70*time.Millisecond)
thread2 := pthread.Create(listener, nil)
input := ""
fmt.Scanln(&input) // Hit return to exit.
thread1.Kill()
thread2.Kill()
}
// Must accept an interface type as this is intended to be a pthread
func listener(args interface{}) {
listener, err := net.Listen("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err) // e.g., connection aborted
continue
}
go handleConn(conn) // handle connections in coroutines
}
}
func handleConn(c net.Conn) {
defer c.Close()
for {
_, err := io.WriteString(c, time.Now().Format("15:04:05\n"))
if err != nil {
return // e.g., client disconnected
}
time.Sleep(1 * time.Second)
}
}
func spinner(args interface{}) {
delay := args.(time.Duration)
for {
for _, r := range `-\|/` {
fmt.Printf("\r%c", r)
time.Sleep(delay)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment