在下面的 GoLang 程序中,我嘗試使用 2*N 個 goroutines(每個男人和女人 1 個)來實現N 個男人和 N 個女人的穩定婚姻問題。該程序嚴格遵循程序定義,因為每個 goroutine(讀作“每個男人”)通過通道向所需的女人 goroutine 發送消息,而女人 goroutine 又拒絕/接受他的提議。我希望該程序可以輕松地在設置runtime.GOMAXPROCS(4)時在多個線程上進行調度,但是它仍然(幾乎)在完全相同的時間運行(并且運行 linux 命令time仍然顯示 CPU 使用率100%而不是預期400%)package mainimport ( "fmt" "runtime" "time")const N = 500type human struct { pref [N]int phone chan int cur_eng int cur_num int id int}var men = [N]human{}var women = [N]human{}func man(id int) { guy := &men[id] for { runtime.Gosched() for j := guy.cur_num + 1; j < N; j++ { guy.cur_num = j girl := &women[guy.pref[guy.cur_num]] girl.phone <- guy.id msg := <-guy.phone if msg == 1 { guy.cur_eng = guy.pref[guy.cur_num] break } } select { case <-guy.phone: guy.cur_eng = -1 } }}func woman(id int, termi chan bool) { girl := &women[id] for { runtime.Gosched() select { case msg := <-girl.phone: if msg >= 0 { if girl.cur_eng == -1 { men[msg].phone <- 1 girl.cur_eng = msg termi <- true } else if girl.pref[girl.cur_eng] < girl.pref[msg] { men[msg].phone <- 0 } else { men[msg].phone <- 1 men[girl.cur_eng].phone <- -10 girl.cur_eng = msg } } } }}
- 1 回答
- 0 關注
- 206 瀏覽
添加回答
舉報
0/150
提交
取消