Юлия обнови решението на 09.11.2015 22:09 (преди над 2 години)
+package main
+
+import (
+ "container/list"
+ "fmt"
+)
+
+func OrderedLogDrainer(channels chan (chan string)) chan string {
+ result := make(chan string, 1000)
+ go divideChannels(channels, result)
+ return result
+}
+
+func divideChannels(channels chan (chan string), result chan string) {
+ threadSafeQueue := make(chan struct{}, 1)
+ channelsInQueue := make(chan struct{}, 100)
+ index := 0
+ queue := list.New()
+
+ go writeAll(queue, result, channelsInQueue, threadSafeQueue)
+ for channel := range channels {
+ channelResult := make(chan string, 100)
+ threadSafeQueue <- struct{}{}
+ queue.PushBack(channelResult)
+ <-threadSafeQueue
+ channelsInQueue <- struct{}{}
+ index = index + 1
+ go drainChannel(channel, channelResult, index)
+
+ }
+ close(channelsInQueue)
+}
+
+func drainChannel(channel, column chan string, index int) {
+ for log := range channel {
+ column <- fmt.Sprintf("%d\t%s", index, log)
+ }
+ close(column)
+}
+
+func writeAll(queue *list.List, result chan string, channelsInQueue, threadSafeQueue chan struct{}) {
+ for _ = range channelsInQueue {
+ threadSafeQueue <- struct{}{}
+ channel := (queue.Remove(queue.Front())).(chan string)
+ <-threadSafeQueue
+ for element := range channel {
+ result <- element
+ }
+ }
+ close(result)
+}
Супер е, много ми харесва как ползваш threadSafeQueue
като mutex! Единствено искам да ти насоча вниманието към последното правило от условието. Казали сме, че във всеки лог ще има по максимум 100 съобщения, но няма ограничение за броя логове.