已关闭,此问题需要details or clarity,目前不接受回答。
**想要改进此问题吗?**通过editing this post添加详细信息并澄清问题。
6天前关闭
Improve this question的
我有三个函数可以打印First
,Second
和Third
。我想按照First
然后Second
然后Third
的顺序通过并发(通道)打印它。
我正面临着问题,使他们在秩序。有人可以帮助我在这方面,我们如何才能实现排序?
package main
import (
"fmt"
"sync"
)
type firstSecondThird struct {
n int
}
var (
wg sync.WaitGroup
first chan bool
second chan bool
third chan bool
)
func init() {
first = make(chan bool)
second = make(chan bool)
// third = make(chan bool)
}
func (fn firstSecondThird) first() {
defer wg.Done()
for i := 0; i < fn.n; i++ {
fmt.Print("First")
first <- true
}
}
func (fn firstSecondThird) second() {
defer wg.Done()
for i := 0; i < fn.n; i++ {
<-first
fmt.Print("Second")
second <- true
}
}
func (fn firstSecondThird) third() {
defer wg.Done()
for i := 0; i < fn.n; i++ {
<-second
fmt.Print("Third")
// third <- true
}
}
func main() {
firstSecondThird := firstSecondThird{
n: 4,
}
wg.Add(2)
go firstSecondThird.first()
go firstSecondThird.second()
go firstSecondThird.third()
// <-third
wg.Wait()
}
字符串
输出:
FirstFirstSecondSecondFirstThirdThirdSecondThirdFirstSecond%
型
编辑:
很抱歉问了这个愚蠢的问题。最初的问题是只打印一次第一个第二个第三个。所以它更容易做到。我试图弄清楚如果做n次,我们是否可以实现排序。谢谢你澄清它。好吧,以特定的顺序排序它们并不意味着并发,而且会增加复杂性。唯一可以做的是以随机顺序将它们分组在一起。
package main
import (
"fmt"
"sync"
)
type firstSecondThird struct {
n int
}
var (
wg sync.WaitGroup
fchan chan chan bool
schan chan chan bool
tchan chan chan bool
)
func init() {
fchan = make(chan chan bool)
schan = make(chan chan bool)
tchan = make(chan chan bool)
}
func (firstSecondThird) barrier(fchan, schan, tchan chan chan bool) {
for {
f := <-fchan
s := <-schan
t := <-tchan
f <- true
s <- true
t <- true
}
}
func (fn firstSecondThird) first(fchan chan chan bool) {
defer wg.Done()
for i := 0; i < fn.n; i++ {
first := make(chan bool)
fchan <- first
<-first
fmt.Print("First")
}
}
func (fn firstSecondThird) second(schan chan chan bool) {
defer wg.Done()
for i := 0; i < fn.n; i++ {
second := make(chan bool)
schan <- second
<-second
fmt.Print("Second")
}
}
func (fn firstSecondThird) third(tchan chan chan bool) {
defer wg.Done()
for i := 0; i < fn.n; i++ {
third := make(chan bool)
tchan <- third
<-third
fmt.Print("Third")
}
}
func main() {
firstSecondThird := firstSecondThird{
n: 4,
}
go firstSecondThird.barrier(fchan, schan, tchan)
wg.Add(3)
go firstSecondThird.first(fchan)
go firstSecondThird.second(schan)
go firstSecondThird.third(tchan)
wg.Wait()
}
型
输出:
FirstThirdSecondSecondFirstThirdThirdFirstSecondSecondFirstThird%
型
2条答案
按热度按时间blpfk2vs1#
您正在尝试使用通道协调执行顺序,这并不容易。请注意,对于
n
进程:所以循环应该看起来像这样(k是函数的索引):
字符串
egmofgnx2#
字符串