在开发libcurl程序中,发现有时候显示调用curl_global_init或不显示调用curl_global_init(都可以,那这个原因是?这个功能是否必要?
官方文档:
This function must be called at least once within a program (a program is all the code that shares a memory space) before the program calls any other function in libcurl. The environment it sets up is constant for the life of the program and is the same for every program,so multiple calls have the same effect as one call.
但请注意,在curl_easy_init的文件中:
If you did not already call curl_global_init(3),curl_easy_init(3) does it automatically. This may be lethal in multi-threaded cases,since curl_global_init(3) is not thread-safe,and it may result in resource problems because there is no corresponding cleanup.
上面两段简单来说就是当curl_global_init没有被调用时,curl_easy_init会调用curl_global_init。所以说,不是我们没有调用,只是我们没有显示调用curl_global_init而已。
但是由于curl_global_init是非线程安全的,所以在多线程的程中,如果利用curl_easy_init调用curl_global_init,可能会使程序奔溃,所以在多线程中,我们必需要调显示调用curl_global_init,再调用curl_easy_init获取相关的curl句柄去操作。