英文:
Are Chdir and Setuid and Setgid thread safe?
问题
os.Chdir
、os.Setuid
和os.Setgid
在Go语言中是线程安全的吗?
换句话说,如果我在两个并行运行的goroutine中分别调用os.Chdir
(或其他两个函数),它会为工作的goroutine改变目录,还是整个进程(可能会引起问题)?
我在文档中找不到相关信息。
英文:
Are os. Chdir
, os.Setuid
and os.Setgid
thread-safe in Go?
In otherwords, if I do a os.Chdir
(or the other two functions) in two different goroutines running in parallel, is it going change directory for the working goroutine or the whole process (which can cause problems)?
I couldn't find any information in the documentation.
答案1
得分: 6
在底层,os.Chdir
只是调用了chdir()
系统调用:
211 func Chdir(dir string) error {
212 if e := syscall.Chdir(dir); e != nil {
213 return &PathError{"chdir", dir, e}
214 }
215 return nil
216 }
因此,它会影响整个进程。os.Setuid
和os.Setgid
也是如此。
可能可以安全地同时从多个goroutine调用它们,因为执行系统调用会暂停调度器;但要注意竞态条件。
英文:
Under the hood, os.Chdir
just calls the chdir()
system call:
211 func Chdir(dir string) error {
212 if e := syscall.Chdir(dir); e != nil {
213 return &PathError{"chdir", dir, e}
214 }
215 return nil
216 }
So it affects the entire process. The same is true for os.Setuid
and os.Setgid
.
It is probably safe to call these from multiple goroutines at the same time, because executing a system call halts the scheduler; but beware of race conditions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论