//to create three threads within A, B, C, three threads alternating output Numbers between 1 to N,
//A thread output 1,4,7... , thread 2 B,5,8... , C thread output 3,6,9... ,
//the end result is: 1, 2, 3, 4, 5... N
CodePudding user response:
Nothing interesting topic, want to do? Want to three thread synchronization alternating output? Then why do you want to use three threads?If it is complicated by the output, so thinking about the following
Define a total var arrresult int []
A coroutines:
Initial value=1, 3, each time the loop is greater than N, arrresult=append (arrresult, produce value) (lock)
B coroutines:
Initial value=2, 3, each time the loop is greater than N, arrresult=append (arrresult, produce value) (lock)
C coroutines:
Initial value=3, 3, each time the loop is greater than N, arrresult=append (arrresult, produce value) (lock)
The last to sort the output arrresult,
CodePudding user response:
This problem is really do not have what meaning, take the channel congestion control coroutines, far from what locks (of course, can also be controlled with the lock)package main
The import "FMT"
N int (func printNumber) {
The CHS: []=chan int {
Make chan (int),//use to block A go func
Make chan (int),//use the go to block B func
Make chan (int),//use to block C go func
Make chan (int),//use to block the main
}
Go func (ch [] chan int, the from int, to int, finish int) {//A print data from CHS [0] and send next to CHS [1] to awake B
For;; {
The select {
Case data:=& lt; - ch [from] :
FMT. Printf (" A: % d ", data);//use A prefix to check which go func prints the data
If data=N {
https://bbs.csdn.net/topics/=Ch [finish] <0;//if to the end of the data and send a signal to CHS [3] to awake the main
} else {
Ch [to] <- data + 1;
}
}
}
} (CHS, 0, 1, 3);
Go func (ch [] chan int, the from int, to int, finish int) {//B print data from CHS [1] and the send next to CHS [2] to awake C
For;; {
The select {
Case data:=& lt; - ch [from] :
FMT. Printf (" B: % d ", data);
If data=N {
https://bbs.csdn.net/topics/=Ch [finish] <0;//if to the end of the data and send a signal to CHS [3] to awake the main
} else {
Ch [to] <- data + 1;
}
}
}
} (CHS, 1, 2, 3);
Go func (ch [] chan int, the from int, to int, finish int) {//A print data from CHS [2] and the send next to CHS [0] to awake A
For;; {
The select {
Case data:=& lt; - ch [from] :
FMT. Printf (" C: % d ", data);
If data=N {
https://bbs.csdn.net/topics/=Ch [finish] <0;//if to the end of the data and send a signal to CHS [3] to awake the main
} else {
Ch [to] <- data + 1;
}
}
}
} (CHS, 2, 0, 3);
CHS [0] <- 1;//awake A go fun
<- CHS [3];//block the main until all go func finish
For _, ch:=range CHS {//close all channel
Close (ch)
}
FMT. Println ()
}
Func main () {
Var N int.
FMT. Printf (" both please input a number: ");
FMT. The Scanf (" % d ", & amp; N);
PrintNumber (N);
}