libcurl 多線程使用注意事項

1、問題來源,多線程使用Libcurl導致程序跑一段時間後自己退出,沒有明顯的異常。找不到合適的BUG。

 

最後通過查看資料和網上找的一些文章,發現,原來是信號處理的問題:

 

 

CURLOPT_NOSIGNAL


Pass a long. If it is 1, libcurl will not use any functions that install signal handlers or any functions that cause signals to be sent to the process. This option is mainly here to allow multi-threaded unix applications to still set/use all timeout options etc, without risking getting signals. (Added in 7.10)

If this option is set and libcurl has been built with the standard name resolver, timeouts will not occur while the name resolve takes place. Consider building libcurl with c-ares support to enable asynchronous DNS lookups, which enables nice timeouts for name resolves without signals.

Setting CURLOPT_NOSIGNAL to 1 makes libcurl NOT ask the system to ignore SIGPIPE signals, which otherwise are sent by the system when trying to send data to a socket which is closed in the other end. libcurl makes an effort to never cause such SIGPIPEs to trigger, but some operating systems have no way to avoid them and even on those that have there are some corner cases when they may still happen, contrary to our desire. 

 

就是當多個線程都使用超時處理的時候,同時主線程中有sleep或是wait等操作。如果不設置這個選項,libcurl將會發信號打斷這個wait從而導致程序退出。

 

所以,在使用的時候把這個選項設置成1就可以了.

curl_setopt(curl, CURLOPT_NOSIGNAL, 1L);

 

2、關於libcurl庫的初始化和關閉:curl_global_init()和curl_global_cleanup()

這兩個函數並不是線程安全的。所以只能在主線程中進行一次的初始化和清除。

雖然這個不是一定就會有問題,但是如果不這樣處理還是有概率發生的。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章