jeffhung Jun 08, 2010 03:27PM Boost.Random 好複雜不想用,然後熊熊忘計 rand() 同一秒抓到的都是一樣的值。看來還是得乖乖弄個 random generator 來行。
jeffhung 說 Jun 08, 2010 03:51PM 喔,故事是這樣的,既然是 pseudo random,那只要 srand() 的時間差不多(在同一秒),那大家之後所 rand() 得到的 sequence 都會一樣。
jeffhung 說 Jun 08, 2010 03:52PM 所以在很多 processes 甚至跨機器的情況下,大家一起啟動,同時 srand(),然後之後很多事情就會因為 rand() 得到一樣的值而亂了套。
jeffhung 說 Jun 08, 2010 03:58PM avhacker: 這其實也算地雷,只是平常不會寫 multi process 甚至跨機器的程式,所以不容易碰到。但碰到時還是會苦很久才能想通原因。
jeffhung 說 Jun 08, 2010 04:01PM sorry: 同一個 process 用 pthread_self() 也行啊。只是程式寫多了,「慣性」會用 time() 來當 seed,然後就中招了。
fr3@K 說 Jun 08, 2010 04:11PM jeffhung 是還蠻苦的. 給個例子 - 15F 有的 team 不只是 API 要 "C", 連 implementation 都一定要純 "C"
戩天姜 Jun 08, 2010 04:13PM by definition "random" 可以是同一個值啊 想要不同的值,就 hash 一下?雖然同一秒附近一定 rand 出一樣的序列有嚴重的安全性問題,但不知道這是不是 jeffhung 真正關切的部分?
jeffhung 說 Jun 08, 2010 04:22PM augustinus: 那時的設計是,為了避免系統啟動時,大家一起工作而 congestion,所以會用 random number 大家一起亂暫停一下。結果因為上面那地雷而沒有任何效果。
jeffhung 說 Jun 08, 2010 04:26PM Win32 弄 device_random_generator 比較麻煩 (但有 API,沒花時間研究就是了),所以我是在 posix 下用 /dev/random,在 win32 下用 guid_random_generator。
jeffhung 說 Jun 08, 2010 04:27PM 但是 guid_random_generator 也要小心中招,若 guid generator 裡面也採用 pseudo random number 的話...
jeffhung 說 Jun 08, 2010 04:31PM 話說 /dev/random 也是 pseudo 的,然後雖然透過 read() 大家不會都拿到一樣的東西,但 read() 會有 lock...
av. 說 Jun 09, 2010 01:47AM jeffhung: 我沒用過 Boost.Random, 不過看來它在給 seed 這邊其實也沒比較好用,不知道它的優勢是什麼? 不然還是直接用舊的 c api 算了
jeffhung 說 Jun 09, 2010 02:11AM 結果最後讓我覺得 Boost.Random 很複雜的原因是 compile 出一堆 error,細看原來是 -Wshadow 的關係,用 #pragma 把 #include <boost/random.hpp> 包起來就好了。(boost-1.40.0)