gpt4 book ai didi

multithreading - GoLang 程序在单线程上执行,即使使用 GOMAXPROCS(4)

转载 作者:IT王子 更新时间:2023-10-29 01:45:33 24 4
gpt4 key购买 nike

在下面的 GoLang 程序中,我试图实现 stable marriage problem对于 N 个男人和 N 个女人,使用 2*N 个协程(每个男人和女人 1 个)。

程序严格遵循程序定义,因为每个 goroutine(读作“每个男人”)通过 channel 向所需的女性 goroutine 发送消息,而女性 goroutine 反过来拒绝/接受他的提议。我希望该程序可以在设置 runtime.GOMAXPROCS(4) 时轻松地安排在多个线程上,但是它仍然(几乎)在完全相同的时间运行(并且运行 linux 命令 time 仍然显示 100% 的 CPU 使用率,而不是预期的 400%)

package main

import (
"fmt"
"runtime"
"time"
)

const N = 500

type 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
}
}
}
}
}

func main() {
runtime.GOMAXPROCS(8)
for i := 0; i < N; i++ {
men[i] = human{pref: [N]int{}, phone: make(chan int), cur_eng: -1, cur_num: -1, id: i}
for j := 0; j < N; j++ {
fmt.Scanf("%d\n", &(men[i].pref[j]))
}
}
for i := 0; i < N; i++ {
women[i] = human{pref: [N]int{}, phone: make(chan int), cur_eng: -1, cur_num: -1, id: i}
for j := 0; j < N; j++ {
t := 0
fmt.Scanf("%d\n", &t)
women[i].pref[t] = j
}
}
termi := make(chan bool)
for i := 0; i < N; i++ {
go man(i)
go woman(i, termi)
}
for i := 0; i < N; i++ {
<-termi
}
time.Sleep(100 * time.Millisecond)
for i := 0; i < N; i++ {
fmt.Printf("%d %d\n", i, men[i].cur_eng)
}
}

编辑:我制作的程序的串行实现是here .时间比较显示两者的运行时间几乎相同(串行为 1.27 秒,以上为 1.30 秒)。

此外,并行实现所遵循的算法是根据 this 制定的以及我能理解的(我使用 goroutines 因为我不知道如何使用 MPI)。如果可能,请随时提出替代实现方案(并行)。

上面的程序需要以下文件作为输入文件:https://drive.google.com/file/d/0B6jsnt965ZwrWlV1OE9LLVA1LUk/view?usp=sharing

最佳答案

我认为您提供的输入文件需要花费那么多时间才能被程序读取(通过每行 scanf)。

关于multithreading - GoLang 程序在单线程上执行,即使使用 GOMAXPROCS(4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com