读/dev/urandom是线程安全的吗? [英] Is reading /dev/urandom thread-safe?

查看:454
本文介绍了读/dev/urandom是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

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

解决方案

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

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

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_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.

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是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆