Last active
February 13, 2021 01:56
-
-
Save shazadbrohi/41e4aa59cb11eac5822b8e4d84ac974c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ("fmt" | |
"net/http" | |
"log" | |
"io/ioutil" | |
"io" | |
"sync" | |
"os" | |
) | |
func fetchUrl(url string, send_channel chan<- string){ | |
response, err := http.Get(url) | |
if(err != nil){ | |
log.Fatal(err) | |
} | |
bytes, err := io.Copy(ioutil.Discard, response.Body) | |
response.Body.Close() | |
if(err != nil){ | |
log.Fatal(err) | |
} | |
send_channel <- fmt.Sprintf("Downloaded %d bytes from URL %s", bytes, url) | |
} | |
func worker(pid int, wg *sync.WaitGroup, file *os.File){ | |
defer wg.Done() | |
fmt.Printf("Worker Process %d writing to file...\n", pid) | |
content := fmt.Sprintf("Worker %d wrote to the file\n", pid) | |
file.WriteString(content) | |
file.Sync() | |
} | |
func main(){ | |
urls := [2]string{"https://vmware.com", "https://dell.com"} | |
var receive_channel string | |
send_channel := make(chan string) | |
var wg sync.WaitGroup | |
f, err := os.Create("/tmp/concurrency_in_go.txt") | |
if err != nil{ | |
panic(err) | |
} | |
defer f.Close() | |
for i := 1; i <= 3; i++ { | |
wg.Add(1) | |
go worker(i, &wg, f) | |
} | |
wg.Wait() | |
for _, url := range urls { | |
go fetchUrl(url, send_channel) | |
} | |
for _, url := range urls { | |
fmt.Println("Fetching channel content for URL: ", url) | |
receive_channel = <-send_channel | |
fmt.Println(receive_channel) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment