shared-connection-cache.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. /* <DESC>
  23. * Connection cache shared between easy handles with the share interface
  24. * </DESC>
  25. */
  26. #include <stdio.h>
  27. #include <curl/curl.h>
  28. static void my_lock(CURL *handle, curl_lock_data data,
  29. curl_lock_access laccess, void *useptr)
  30. {
  31. (void)handle;
  32. (void)data;
  33. (void)laccess;
  34. (void)useptr;
  35. fprintf(stderr, "-> Mutex lock\n");
  36. }
  37. static void my_unlock(CURL *handle, curl_lock_data data, void *useptr)
  38. {
  39. (void)handle;
  40. (void)data;
  41. (void)useptr;
  42. fprintf(stderr, "<- Mutex unlock\n");
  43. }
  44. int main(void)
  45. {
  46. CURLSH *share;
  47. int i;
  48. share = curl_share_init();
  49. curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);
  50. curl_share_setopt(share, CURLSHOPT_LOCKFUNC, my_lock);
  51. curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, my_unlock);
  52. /* Loop the transfer and cleanup the handle properly every lap. This will
  53. still reuse connections since the pool is in the shared object! */
  54. for(i = 0; i < 3; i++) {
  55. CURL *curl = curl_easy_init();
  56. if(curl) {
  57. CURLcode res;
  58. curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/");
  59. /* use the share object */
  60. curl_easy_setopt(curl, CURLOPT_SHARE, share);
  61. /* Perform the request, res will get the return code */
  62. res = curl_easy_perform(curl);
  63. /* Check for errors */
  64. if(res != CURLE_OK)
  65. fprintf(stderr, "curl_easy_perform() failed: %s\n",
  66. curl_easy_strerror(res));
  67. /* always cleanup */
  68. curl_easy_cleanup(curl);
  69. }
  70. }
  71. curl_share_cleanup(share);
  72. return 0;
  73. }