Home  >  Article  >  Backend Development  >  Is Golang crypto/rand thread safe?

Is Golang crypto/rand thread safe?

王林
王林forward
2024-02-09 12:45:08965browse

Golang 加密/兰德线程安全吗?

Golang is a programming language known for its efficiency and concurrency. However, Golang’s encryption and thread safety have always been the focus of developers. In this article, php editor Banana will share some opinions and suggestions about Golang encryption and Golang thread safety. We will explore Golang's encryption features and how to ensure thread safety to help developers better understand and apply Golang. Whether you are a beginner or an experienced developer, this article will provide you with valuable information and guidance.

Question content

The source of math/rand.rand states that read is not thread-safe (when sharing the source). What about crypto/rand? The source code states that it uses getrandom(2) or /dev/urandom, but it's not clear what happens with concurrent calls.

Update: Comments help clarify the difference

crypto/rand.Reader.Read(b []byte)
crypto/rand.Read(b []byte)

Thread safety:

  1. Concurrent callsreadwill panic?
  2. Will the random sequence be maintained when called concurrently? Or can duplicate content be served to concurrent callers?

Solution

  1. rand.Reader from crypto/rand Must be safe for concurrent access as it is defined as a "global cryptographically secure random number generator" Shared instance". There is no way to synchronize its usage between packages.
  2. rand.Read from crypto/rand is safe because rand.Reader is safe and it does not access Any other shared status.

The above is the detailed content of Is Golang crypto/rand thread safe?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete