|
| 1 | +/* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs libmongoc-1.0) */ |
| 2 | + |
| 3 | +/* ./example-pool [CONNECTION_STRING] */ |
| 4 | + |
| 5 | +#include <mongoc.h> |
| 6 | +#include <pthread.h> |
| 7 | +#include <stdio.h> |
| 8 | + |
| 9 | +static pthread_mutex_t mutex; |
| 10 | +static bool in_shutdown = false; |
| 11 | + |
| 12 | +static void * |
| 13 | +worker (void *data) |
| 14 | +{ |
| 15 | + mongoc_client_pool_t *pool = data; |
| 16 | + mongoc_client_t *client; |
| 17 | + bson_t ping = BSON_INITIALIZER; |
| 18 | + bson_error_t error; |
| 19 | + bool r; |
| 20 | + |
| 21 | + BSON_APPEND_INT32 (&ping, "ping", 1); |
| 22 | + |
| 23 | + while (true) { |
| 24 | + client = mongoc_client_pool_pop (pool); |
| 25 | + /* Do something with client. If you are writing an HTTP server, you |
| 26 | + * probably only want to hold onto the client for the portion of the |
| 27 | + * request performing database queries. |
| 28 | + */ |
| 29 | + r = mongoc_client_command_simple (client, "admin", &ping, NULL, NULL, |
| 30 | + &error); |
| 31 | + |
| 32 | + if (!r) { |
| 33 | + fprintf (stderr, "%s\n", error.message); |
| 34 | + } |
| 35 | + |
| 36 | + mongoc_client_pool_push (pool, client); |
| 37 | + |
| 38 | + pthread_mutex_lock (&mutex); |
| 39 | + if (in_shutdown || !r) { |
| 40 | + pthread_mutex_unlock (&mutex); |
| 41 | + break; |
| 42 | + } |
| 43 | + |
| 44 | + pthread_mutex_unlock (&mutex); |
| 45 | + } |
| 46 | + |
| 47 | + bson_destroy (&ping); |
| 48 | + return NULL; |
| 49 | +} |
| 50 | + |
| 51 | +int main (int argc, char *argv[]) |
| 52 | +{ |
| 53 | + const char *uristr = "mongodb://127.0.0.1/?appname=pool-example"; |
| 54 | + mongoc_uri_t *uri; |
| 55 | + mongoc_client_pool_t *pool; |
| 56 | + pthread_t threads[10]; |
| 57 | + unsigned i; |
| 58 | + void *ret; |
| 59 | + |
| 60 | + pthread_mutex_init (&mutex, NULL); |
| 61 | + mongoc_init (); |
| 62 | + |
| 63 | + if (argc > 1) { |
| 64 | + uristr = argv [1]; |
| 65 | + } |
| 66 | + |
| 67 | + uri = mongoc_uri_new (uristr); |
| 68 | + if (!uri) { |
| 69 | + fprintf (stderr, "Failed to parse URI: \"%s\".\n", uristr); |
| 70 | + return EXIT_FAILURE; |
| 71 | + } |
| 72 | + |
| 73 | + pool = mongoc_client_pool_new (uri); |
| 74 | + mongoc_client_pool_set_error_api (pool, 2); |
| 75 | + |
| 76 | + for (i = 0; i < 10; i++) { |
| 77 | + pthread_create (&threads[i], NULL, worker, pool); |
| 78 | + } |
| 79 | + |
| 80 | + sleep (10); |
| 81 | + pthread_mutex_lock (&mutex); |
| 82 | + in_shutdown = true; |
| 83 | + pthread_mutex_unlock (&mutex); |
| 84 | + |
| 85 | + for (i = 0; i < 10; i++) { |
| 86 | + pthread_join (threads[i], &ret); |
| 87 | + } |
| 88 | + |
| 89 | + mongoc_client_pool_destroy (pool); |
| 90 | + mongoc_uri_destroy (uri); |
| 91 | + |
| 92 | + mongoc_cleanup (); |
| 93 | + |
| 94 | + return 0; |
| 95 | +} |
0 commit comments