Is Golang crypto/rand thread safe?

王林
Release: 2024-02-09 12:45:08
forward
964 people have browsed it

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)
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!