Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Paul reznikov/do tasks #49

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/go-concurrency-exercises.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 8 additions & 3 deletions 0-limit-crawler/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,20 @@ package main
import (
"fmt"
"sync"
"time"
)

// Crawl uses `fetcher` from the `mockfetcher.go` file to imitate a
// real crawler. It crawls until the maximum depth has reached.
func Crawl(url string, depth int, wg *sync.WaitGroup) {
func Crawl(url string, depth int, wg *sync.WaitGroup, ticker <-chan time.Time) {
defer wg.Done()

if depth <= 0 {
return
}

<-ticker

body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
Expand All @@ -35,14 +38,16 @@ func Crawl(url string, depth int, wg *sync.WaitGroup) {
for _, u := range urls {
// Do not remove the `go` keyword, as Crawl() must be
// called concurrently
go Crawl(u, depth-1, wg)
go Crawl(u, depth-1, wg, ticker)
}
}

func main() {
var wg sync.WaitGroup

ticker := time.NewTicker(1 * time.Second)

wg.Add(1)
Crawl("http://golang.org/", 4, &wg)
Crawl("http://golang.org/", 4, &wg, ticker.C)
wg.Wait()
}
29 changes: 19 additions & 10 deletions 1-producer-consumer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,48 @@ package main

import (
"fmt"
"sync"
"time"
)

func producer(stream Stream) (tweets []*Tweet) {
func producer(stream Stream, tweetsChan chan<- *Tweet) {
for {
tweet, err := stream.Next()
if err == ErrEOF {
return tweets
close(tweetsChan)
return
}

tweets = append(tweets, tweet)
tweetsChan <- tweet
}
}

func consumer(tweets []*Tweet) {
for _, t := range tweets {
if t.IsTalkingAboutGo() {
fmt.Println(t.Username, "\ttweets about golang")
func consumer(tweetsChan <-chan *Tweet, wg *sync.WaitGroup) {
defer wg.Done()

for tweet := range tweetsChan {
if tweet.IsTalkingAboutGo() {
fmt.Println(tweet.Username, "\ttweets about golang")
} else {
fmt.Println(t.Username, "\tdoes not tweet about golang")
fmt.Println(tweet.Username, "\tdoes not tweet about golang")
}
}
}

func main() {
start := time.Now()
stream := GetMockStream()
var wg sync.WaitGroup

tweetsChan := make(chan *Tweet)

// Producer
tweets := producer(stream)
go producer(stream, tweetsChan)

wg.Add(1)
// Consumer
consumer(tweets)
go consumer(tweetsChan, &wg)
wg.Wait()

fmt.Printf("Process took %s\n", time.Since(start))
}
16 changes: 16 additions & 0 deletions 2-race-in-cache/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package main

import (
"container/list"
"sync"
"testing"
)

Expand All @@ -32,34 +33,49 @@ type KeyStoreCache struct {
cache map[string]*list.Element
pages list.List
load func(string) string
mutex *sync.Mutex
}

// New creates a new KeyStoreCache
func New(load KeyStoreCacheLoader) *KeyStoreCache {
return &KeyStoreCache{
load: load.Load,
cache: make(map[string]*list.Element),
mutex: &sync.Mutex{},
}
}

// Get gets the key from cache, loads it from the source if needed
func (k *KeyStoreCache) Get(key string) string {

k.mutex.Lock()
defer k.mutex.Unlock()

if e, ok := k.cache[key]; ok {
k.pages.MoveToFront(e)
return e.Value.(page).Value
}

// Miss - load from database and save it in cache
p := page{key, k.load(key)}

// if cache is full remove the least used item
if len(k.cache) >= CacheSize {

end := k.pages.Back()

// remove from map
delete(k.cache, end.Value.(page).Key)

// remove from list
k.pages.Remove(end)

}

k.pages.PushFront(p)

k.cache[key] = k.pages.Front()

return p.Value
}

Expand Down
2 changes: 1 addition & 1 deletion 2-race-in-cache/mockserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func RunMockServer(cache *KeyStoreCache, t *testing.T) {
go func(i int) {
value := cache.Get("Test" + strconv.Itoa(i))
if t != nil {
if value != "Test" + strconv.Itoa(i) {
if value != "Test"+strconv.Itoa(i) {
t.Errorf("Incorrect db response %v", value)
}
}
Expand Down
34 changes: 32 additions & 2 deletions 3-limit-service-time/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

package main

import "time"

// User defines the UserModel. Use this to check whether a User is a
// Premium user or not
type User struct {
Expand All @@ -21,8 +23,36 @@ type User struct {
// HandleRequest runs the processes requested by users. Returns false
// if process had to be killed
func HandleRequest(process func(), u *User) bool {
process()
return true
var (
startReqProc, endReqProc time.Time
)

done := make(chan struct{})

go func() {
startReqProc = time.Now()
process()
endReqProc = time.Now()
done <- struct{}{}
}()

if u.IsPremium {
<-done
return true
}

select {
case <-time.After(10 * time.Second):
return false
case <-done:
diff := endReqProc.Sub(startReqProc).Seconds()
u.TimeUsed += int64(diff)
if u.TimeUsed <= 10 {
return true
}
return false
}

}

func main() {
Expand Down
30 changes: 29 additions & 1 deletion 4-graceful-sigint/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,38 @@

package main

import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)

func main() {
sigsStop := make(chan os.Signal)

signal.Notify(sigsStop, syscall.SIGINT, syscall.SIGTERM)

// Create a process
proc := MockProcess{}

fmt.Println("The program is running. Press Ctrl+C to complete.")

// Run the process (blocking)
proc.Run()
go proc.Run()
sigStop := <-sigsStop
fmt.Printf("\nA signal has been received: %v.\n", sigStop)

go proc.Stop()
fmt.Println("We are completing the work correctly...")

select {
case <-time.After(5 * time.Second):
fmt.Println("\nThe correct shutdown has been completed.")
case sigStop = <-sigsStop:
fmt.Printf("\nA signal has been received: %v. Early termination of work.", sigStop)
}

os.Exit(0)
}
Loading