Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(119904)

Unified Diff: Python/random.c

Issue 18756: os.urandom() fails under high load
Patch Set: Created 6 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « Python/pythonrun.c ('k') | no next file » | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
--- a/Python/random.c
+++ b/Python/random.c
@@ -90,6 +90,7 @@ vms_urandom(unsigned char *buffer, Py_ss
#if !defined(MS_WINDOWS) && !defined(__VMS)
+static int urandom_fd = -1;
/* Read size bytes from /dev/urandom into buffer.
Call Py_FatalError() on error. */
@@ -133,14 +134,26 @@ dev_urandom_python(char *buffer, Py_ssiz
if (size <= 0)
return 0;
- Py_BEGIN_ALLOW_THREADS
- fd = open("/dev/urandom", O_RDONLY);
- Py_END_ALLOW_THREADS
- if (fd < 0)
- {
- PyErr_SetString(PyExc_NotImplementedError,
- "/dev/urandom (or equivalent) not found");
- return -1;
+ if (urandom_fd >= 0)
+ fd = urandom_fd;
+ else {
+ Py_BEGIN_ALLOW_THREADS
+ fd = open("/dev/urandom", O_RDONLY);
+ Py_END_ALLOW_THREADS
+ if (fd < 0)
+ {
+ PyErr_SetString(PyExc_NotImplementedError,
+ "/dev/urandom (or equivalent) not found");
+ return -1;
+ }
+ if (urandom_fd >= 0) {
+ /* urandom_fd was initialized by another thread while we were
+ not holding the GIL, keep it. */
+ close(fd);
+ fd = urandom_fd;
+ }
+ else
+ urandom_fd = fd;
}
Py_BEGIN_ALLOW_THREADS
@@ -164,12 +177,20 @@ dev_urandom_python(char *buffer, Py_ssiz
PyErr_Format(PyExc_RuntimeError,
"Failed to read %zi bytes from /dev/urandom",
size);
- close(fd);
return -1;
}
- close(fd);
return 0;
}
+
+static void
+dev_urandom_close(void)
+{
+ if (urandom_fd >= 0) {
+ close(urandom_fd);
+ urandom_fd = -1;
+ }
+}
+
#endif /* !defined(MS_WINDOWS) && !defined(__VMS) */
/* Fill buffer with pseudo-random bytes generated by a linear congruent
@@ -267,3 +288,11 @@ void
#endif
}
}
+
+void
+_PyRandom_Fini(void)
+{
+#if !defined(MS_WINDOWS) && !defined(__VMS)
+ dev_urandom_close();
+#endif
+}
« no previous file with comments | « Python/pythonrun.c ('k') | no next file » | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+