读/ dev / urandom线程安全吗?

时间:2021-04-05 21:01:09

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?

如果没有,我如何使其线程安全?

1 个解决方案

#1


10  

As long as each execution of the function is in its own thread (i.e., the local variables number, urandom, bytes_read are 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/urandom can be opened simultaneously from multiple processes, so that's okay.

只要函数的每次执行都在自己的线程中(即,局部变量号,urandom,bytes_read不在线程之间共享),我就看不到任何线程安全问题。然后每个线程都有自己的文件描述符到/ dev / urandom。 / dev / urandom可以从多个进程同时打开,所以没关系。

By the way, /dev/urandom can fail to open, and your code should deal with it. Some causes are: running out of available file descriptors; /dev not properly mounted (although in this case you have bigger problems); your program is being run in a special chroot which denies access to any devices; etc.

顺便说一下,/ dev / urandom可能无法打开,你的代码应该处理它。一些原因是:用完了可用的文件描述符; / dev没有正确安装(虽然在这种情况下你有更大的问题);你的程序是在一个特殊的chroot中运行的,它拒绝访问任何设备;等等

#1


10  

As long as each execution of the function is in its own thread (i.e., the local variables number, urandom, bytes_read are 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/urandom can be opened simultaneously from multiple processes, so that's okay.

只要函数的每次执行都在自己的线程中(即,局部变量号,urandom,bytes_read不在线程之间共享),我就看不到任何线程安全问题。然后每个线程都有自己的文件描述符到/ dev / urandom。 / dev / urandom可以从多个进程同时打开,所以没关系。

By the way, /dev/urandom can fail to open, and your code should deal with it. Some causes are: running out of available file descriptors; /dev not properly mounted (although in this case you have bigger problems); your program is being run in a special chroot which denies access to any devices; etc.

顺便说一下,/ dev / urandom可能无法打开,你的代码应该处理它。一些原因是:用完了可用的文件描述符; / dev没有正确安装(虽然在这种情况下你有更大的问题);你的程序是在一个特殊的chroot中运行的,它拒绝访问任何设备;等等