duanba2001 2011-11-27 15:55
浏览 11
已采纳

Go编程语言相互并发执行

I have two concurrent go routines like below,

Routine 1{                                                  

routine procedure   

critical section{                                                     
}

routine procedure                        
} 

Routine 2{                                                  

routine procedure   

critical section{                                                     
}

routine procedure                       
} 

Is it possible by using some go inbuilt functions to implement critical section ?

  • 写回答

6条回答 默认 最新

  • douxing2156 2011-11-28 12:15
    关注

    Your question:

    I have N concurrent go routines (all more or less same purpose). Each of those have a critical section. Before entering critical section, each routine just do some message sending job. When it enters critical section, I need all other routines must stop execution until it exits critical section. Is it possible by using any library function in GO?

    What you are asking about (to force a stop on all other goroutines while one goroutine is in the critical section) is not typical in Go programs. There is no library function to stop all other goroutines, so you will need to stop them by designing proper synchronization among goroutines in your program. The typical scenario is for all goroutines to (potentially) run concurrently, except for those goroutines that are blocked somehow.

    To control concurrent access to a shared resource in a Go program you can use Go channels, the "sync" package, pipes, or network connections.

    Using sync.Mutex, the Go code may look like this (but please keep in mind that, whenever possible, Go programs should preferably use Go channels instead of mutexes):

    package main
    
    import "sync"
    
    var m sync.Mutex
    var wg sync.WaitGroup
    
    func routine1() {
        ... do something ...
    
        m.Lock()
        ... critical section (access the shared resource here) ...
        m.Unlock()
    
        ... do something ...
        wg.Done()
    }
    
    func routine2() {
        ... do something ...
    
        m.Lock()
        ... critical section (access the shared resource here) ...
        m.Unlock()
    
        ... do something ...
        wg.Done()
    }
    
    func main() {
        wg.Add(1); go routine1()
        wg.Add(1); go routine2()
        wg.Wait()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法