英文:
how to make Goroutine not Concurrency if Same Function
问题
有没有办法让goroutine按顺序执行(一个接一个)如果它们是相同的函数?
我一开始并不打算使用goroutine。然而,在TCP中使用"os/exec"函数会导致TCP强制停止。因此,我使用goroutine来避免崩溃。但是我仍然希望它们按顺序执行,而不是并发执行。这是我的代码。
func handleTCP(conn net.Conn) {
defer conn.Close()
fmt.Println("handle TCP function")
for {
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
cmdArgs := []string{temp_str, test_press, gh, "sample.csv"}
cmd := exec.Command("calib.exe", cmdArgs...)
wg.Done()
}()
}
}
英文:
Is there any way to make goroutine execute one after another ( one by one) if it was the same function?
I didn't mean to use goroutine firstly. However, "os/exec" function in TCP will cause the tcp forced to stop. Thus I use goroutine to avoid crashing. But I still want them to execute by order, instead of concurrently. Here is my code.
func handleTCP(conn net.Conn) {
defer conn.Close()
fmt.Println("handle TCP function")
for {
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
cmdArgs := []string{temp_str, test_press, gh, "sample.csv"}
cmd := exec.Command("calib.exe", cmdArgs...)
wg.Done()
}()
}
}
答案1
得分: 0
尝试将锁放入函数中,这样可以使它们的执行顺序变为串行。但要记住,wg.Done()必须在函数的第一行的defer下面。
类似这样的代码:
var mu sync.Mutex
func handleTCP(conn net.Conn) {
defer conn.Close()
fmt.Println("handle TCP function")
for {
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
defer mu.Unlock()
cmdArgs := []string{temp_str, test_press, gh, "sample.csv"}
cmd := exec.Command("calib.exe", cmdArgs...)
// 执行命令
}()
}
}
英文:
Try to put the lock into function, it makes theirs execution sequential. But remember about wg.Done() must be under defer at first line of the function.
Something like this:
var mu sync.Mutex
func handleTCP(conn net.Conn) {
defer conn.Close()
fmt.Println("handle TCP function")
for {
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
defer mu.UnLock()
cmdArgs := []string{temp_str, test_press, gh, "sample.csv"}
cmd := exec.Command("calib.exe", cmdArgs...)
}()
}
}
答案2
得分: 0
你可以使用锁(locks)来限制对资源的访问,使其一次只能由一个线程访问,如下所示:
i := 1
iLock := &sync.Mutex{}
for {
go func() {
iLock.Lock()
fmt.Printf("i的值:%d\n", i)
iLock.Unlock()
}()
}
更多示例请参考这里。
不确定你使用WaitGroup
是为了什么目的。如果是为了实现你想要的顺序执行,那么可以将其移除。
英文:
You can use locks to limit access to a resource to one thread at a time as follows
i := 1
iLock = &sync.Mutex{}
for {
go func() {
iLock.Lock()
fmt.Printf("Value of i: %d\n", i)
iLock.Unlock()
}
}
More examples here
Not sure what you are using the WaitGroup
for. If it is to achieve the sequentiality you desire, then it can be removed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论