1MONGOC_CLIENT_POOL_T(3) MongoDB C Driver MONGOC_CLIENT_POOL_T(3)
2
3
4
6 mongoc_client_pool_t - mongoc_client_pool_t
7
8 A connection pool for multi-threaded programs. See connection-pooling.
9
11 typedef struct _mongoc_client_pool_t mongoc_client_pool_t
12
13 mongoc_client_pool_t is the basis for multi-threading in the MongoDB C
14 driver. Since mongoc_client_t structures are not thread-safe, this
15 structure is used to retrieve a new mongoc_client_t for a given thread.
16 This structure is thread-safe.
17
19 example-pool.c.INDENT 0.0
20
21 /* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs
22 * libmongoc-1.0) */
23
24 /* ./example-pool [CONNECTION_STRING] */
25
26 #include <mongoc/mongoc.h>
27 #include <pthread.h>
28 #include <stdio.h>
29
30 static pthread_mutex_t mutex;
31 static bool in_shutdown = false;
32
33 static void *
34 worker (void *data)
35 {
36 mongoc_client_pool_t *pool = data;
37 mongoc_client_t *client;
38 bson_t ping = BSON_INITIALIZER;
39 bson_error_t error;
40 bool r;
41
42 BSON_APPEND_INT32 (&ping, "ping", 1);
43
44 while (true) {
45 client = mongoc_client_pool_pop (pool);
46 /* Do something with client. If you are writing an HTTP server, you
47 * probably only want to hold onto the client for the portion of the
48 * request performing database queries.
49 */
50 r = mongoc_client_command_simple (
51 client, "admin", &ping, NULL, NULL, &error);
52
53 if (!r) {
54 fprintf (stderr, "%s\n", error.message);
55 }
56
57 mongoc_client_pool_push (pool, client);
58
59 pthread_mutex_lock (&mutex);
60 if (in_shutdown || !r) {
61 pthread_mutex_unlock (&mutex);
62 break;
63 }
64
65 pthread_mutex_unlock (&mutex);
66 }
67
68 bson_destroy (&ping);
69 return NULL;
70 }
71
72 int
73 main (int argc, char *argv[])
74 {
75 const char *uri_string = "mongodb://127.0.0.1/?appname=pool-example";
76 mongoc_uri_t *uri;
77 bson_error_t error;
78 mongoc_client_pool_t *pool;
79 pthread_t threads[10];
80 unsigned i;
81 void *ret;
82
83 pthread_mutex_init (&mutex, NULL);
84 mongoc_init ();
85
86 if (argc > 1) {
87 uri_string = argv[1];
88 }
89
90 uri = mongoc_uri_new_with_error (uri_string, &error);
91 if (!uri) {
92 fprintf (stderr,
93 "failed to parse URI: %s\n"
94 "error message: %s\n",
95 uri_string,
96 error.message);
97 return EXIT_FAILURE;
98 }
99
100 pool = mongoc_client_pool_new (uri);
101 mongoc_client_pool_set_error_api (pool, 2);
102
103 for (i = 0; i < 10; i++) {
104 pthread_create (&threads[i], NULL, worker, pool);
105 }
106
107 sleep (10);
108 pthread_mutex_lock (&mutex);
109 in_shutdown = true;
110 pthread_mutex_unlock (&mutex);
111
112 for (i = 0; i < 10; i++) {
113 pthread_join (threads[i], &ret);
114 }
115
116 mongoc_client_pool_destroy (pool);
117 mongoc_uri_destroy (uri);
118
119 mongoc_cleanup ();
120
121 return EXIT_SUCCESS;
122 }
123
124
126 MongoDB, Inc
127
129 2017-present, MongoDB, Inc
130
131
132
133
1341.13.1 Jan 24, 2019 MONGOC_CLIENT_POOL_T(3)