Imported Upstream version 7.59.0
[platform/upstream/curl.git] / docs / examples / shared-connection-cache.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2017, 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.haxx.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 inteface
24  * </DESC>
25  */
26 #include <stdio.h>
27 #include <curl/curl.h>
28
29 static void my_lock(CURL *handle, curl_lock_data data,
30                     curl_lock_access laccess, void *useptr)
31 {
32   (void)handle;
33   (void)data;
34   (void)laccess;
35   (void)useptr;
36   fprintf(stderr, "-> Mutex lock\n");
37 }
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
47 int main(void)
48 {
49   CURL *curl;
50   CURLcode res;
51   CURLSH *share;
52   int i;
53
54   share = curl_share_init();
55   curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);
56
57   curl_share_setopt(share, CURLSHOPT_LOCKFUNC, my_lock);
58   curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, my_unlock);
59
60   /* Loop the transfer and cleanup the handle properly every lap. This will
61      still reuse connections since the pool is in the shared object! */
62
63   for(i = 0; i < 3; i++) {
64     curl = curl_easy_init();
65     if(curl) {
66       curl_easy_setopt(curl, CURLOPT_URL, "https://curl.haxx.se/");
67
68       /* use the share object */
69       curl_easy_setopt(curl, CURLOPT_SHARE, share);
70
71       /* Perform the request, res will get the return code */
72       res = curl_easy_perform(curl);
73       /* Check for errors */
74       if(res != CURLE_OK)
75         fprintf(stderr, "curl_easy_perform() failed: %s\n",
76                 curl_easy_strerror(res));
77
78       /* always cleanup */
79       curl_easy_cleanup(curl);
80     }
81   }
82
83   curl_share_cleanup(share);
84   return 0;
85 }