一看就知道 – 不 Thread-Safe 的 API
Posted on December 1st, 2009 at 13:37 by fr3@K

Very well put :)

當你發現回傳的是一個 char *,又沒有要求你特別 free 他,你是不是就該猜測他是回傳 function 內部的一個 static buffer 了呢?

Via: 從 inet_ntoa 看 thread safe 的 API.

del.icio.us:一看就知道 - 不 Thread-Safe 的 API digg:一看就知道 - 不 Thread-Safe 的 API spurl:一看就知道 - 不 Thread-Safe 的 API newsvine:一看就知道 - 不 Thread-Safe 的 API furl:一看就知道 - 不 Thread-Safe 的 API Y!:一看就知道 - 不 Thread-Safe 的 API 黑米共享書籤:一看就知道 - 不 Thread-Safe 的 API 推推王:一看就知道 - 不 Thread-Safe 的 API
Previous Post
« What Happens When We Lie to the Compiler? «
Next Post
» Another Good Interview Question in C++ »

3 Comments »

Comment #10342

Visual Studio 的骯髒解法是,針對這種 API,就 per thread 建立一個 buffer,指標存在 TLS (thread local storage) 裡,然後回傳之。

於是 upgrade visual studio 版本後,或是一開始就發現,程式很神奇的不會爛掉,但是當 porting 到其它「正常」的平台後,就爛掉了。

Comment by jeffhung — December 1, 2009 @ 14:41


Comment #10351

boost 的 thread_specific_ptr 應該就派的上用場了,不過我沒用過,不敢肯定。

Comment by av — December 4, 2009 @ 1:46


Comment #10353

@av,

jeff 的意思是說 MS 提供的 runtime library 常會做非標準的事情. 例如 inet_ntoa 的回傳字串的實作.

  • POSIX (BSD)
  • … The string is returned in a statically allocated buffer, which subsequent calls will overwrite.

  • WIN32
  • … The string returned is guaranteed to be valid only until the next Windows Sockets function call is made within the same thread.

於是, 在 windows 上的 programmer 並不會知道程式寫錯了, 那些問題也只會在程式要從 windows 跨到其他 platform 時爆炸.

Comment by fr3@K — December 4, 2009 @ 10:06


Comments RSS TrackBack URI

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>