golang & c++ select 同步实现方式

看一个简单的go select 例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import (
"fmt"
"strconv"
"time"
)

func () {
c1:=make(chan string)
c2:=make(chan string)

go func() {
for {
value ,err := <- c1
if err{
fmt.Println("receive value is ",value)

}else{
c2<-"done"
}
}
}()

for i:=0 ;i<5;i++{
time.Sleep(time.Second*2)
c1<-strconv.Itoa(i)
}
close(c1)
<-c2
}

首先对于这个我与这个程序和c++做了一个对比

对于select的相似的实现中,我的实现的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::mutex m;
std::condition_variable cv;
std::queue<int> m_queue;
void work_thread()
{
....
std::unique_lock<std::mutex> lc(m);
cv.wait(lc,[] {return !m_queue.empty()});

//wait_until
...
}
void send_thread()
{
....
cv.notify_one();
....
}

这样的实现方式采用条件的方式模仿了goLang 中的select