This is the code:
unsigned int number; FILE* urandom = fopen('/dev/urandom', 'r'); if (urandom) { size_t bytes_read = fread(&number, 1, sizeof(number), urandom); DCHECK(bytes_read == sizeof(number)); fclose(urandom); } else { NOTREACHED(); }
If not, how do I make it thread-safe?
As long as each execution of the function is in its own thread (i.e., the local variables
number,urandom,bytes_readare not shared between threads), I don’t see any thread-safety problems. Each thread will then have its own file descriptor into/dev/urandom./dev/urandomcan be opened simultaneously from multiple processes, so that’s okay.By the way,
/dev/urandomcan fail to open, and your code should deal with it. Some causes are: running out of available file descriptors;/devnot properly mounted (although in this case you have bigger problems); your program is being run in a specialchrootwhich denies access to any devices; etc.