shared-connection-cache.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. /* <DESC>
  25. * Connection cache shared between easy handles with the share interface
  26. * </DESC>
  27. */
  28. #include <stdio.h>
  29. #include <curl/curl.h>
  30. static void my_lock(CURL *handle, curl_lock_data data,
  31. curl_lock_access laccess, void *useptr)
  32. {
  33. (void)handle;
  34. (void)data;
  35. (void)laccess;
  36. (void)useptr;
  37. fprintf(stderr, "-> Mutex lock\n");
  38. }
  39. static void my_unlock(CURL *handle, curl_lock_data data, void *useptr)
  40. {
  41. (void)handle;
  42. (void)data;
  43. (void)useptr;
  44. fprintf(stderr, "<- Mutex unlock\n");
  45. }
  46. int main(void)
  47. {
  48. CURLSH *share;
  49. int i;
  50. share = curl_share_init();
  51. curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);
  52. curl_share_setopt(share, CURLSHOPT_LOCKFUNC, my_lock);
  53. curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, my_unlock);
  54. /* Loop the transfer and cleanup the handle properly every lap. This will
  55. still reuse connections since the pool is in the shared object! */
  56. for(i = 0; i < 3; i++) {
  57. CURL *curl = curl_easy_init();
  58. if(curl) {
  59. CURLcode res;
  60. curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/");
  61. /* use the share object */
  62. curl_easy_setopt(curl, CURLOPT_SHARE, share);
  63. /* Perform the request, res will get the return code */
  64. res = curl_easy_perform(curl);
  65. /* Check for errors */
  66. if(res != CURLE_OK)
  67. fprintf(stderr, "curl_easy_perform() failed: %s\n",
  68. curl_easy_strerror(res));
  69. /* always cleanup */
  70. curl_easy_cleanup(curl);
  71. }
  72. }
  73. curl_share_cleanup(share);
  74. return 0;
  75. }