|
22 | 22 | <section id="example">
|
23 | 23 | <title>Example</title>
|
24 | 24 | <screen><code mime="text/x-csrc"><![CDATA[#include <mongoc.h>
|
| 25 | +#include <pthread.h> |
| 26 | +
|
| 27 | +static pthread_mutex_t mutex; |
| 28 | +static bool in_shutdown = false; |
25 | 29 |
|
26 | 30 | static void *
|
27 | 31 | worker (void *data)
|
28 | 32 | {
|
29 | 33 | mongoc_client_pool_t *pool = data;
|
30 | 34 | mongoc_client_t *client;
|
31 | 35 |
|
32 |
| - do { |
| 36 | + while (true) { |
33 | 37 | client = mongoc_client_pool_pop (pool);
|
34 | 38 | /*
|
35 | 39 | * Do something with client. If you are writing an HTTP server, you
|
36 | 40 | * probably only want to hold onto the client for the portion of the
|
37 | 41 | * request performing database queries.
|
38 | 42 | */
|
39 | 43 | mongoc_client_pool_push (pool, client);
|
40 |
| - } while (!inShutdown); |
41 | 44 |
|
42 |
| - return NULL; |
| 45 | + pthread_mutex_lock (&mutex); |
| 46 | + if (in_shutdown) { |
| 47 | + pthread_mutex_unlock (&mutex); |
| 48 | + return NULL; |
| 49 | + } |
| 50 | +
|
| 51 | + pthread_mutex_unlock (&mutex); |
| 52 | + } |
43 | 53 | }
|
44 | 54 |
|
45 | 55 | int main (int argc, char *argv[])
|
46 | 56 | {
|
47 | 57 | mongoc_client_pool_t *pool;
|
48 | 58 | mongoc_uri_t *uri;
|
49 |
| - pthread_t thread[10]; |
| 59 | + pthread_t threads[10]; |
50 | 60 | unsigned i;
|
51 | 61 | void *ret;
|
52 | 62 |
|
| 63 | + pthread_mutex_init (&mutex, NULL); |
53 | 64 | mongoc_init ();
|
54 | 65 |
|
55 |
| - uri = mongoc_uri_new ("mongodb://mdb1.example.com/?minPoolSize=16"); |
| 66 | + uri = mongoc_uri_new ("mongodb://localhost/?minPoolSize=16"); |
56 | 67 | pool = mongoc_client_pool_new (uri);
|
57 | 68 |
|
58 | 69 | for (i = 0; i < 10; i++) {
|
59 |
| - pthread_create (&thread, NULL, worker, pool); |
| 70 | + pthread_create (&threads[i], NULL, worker, pool); |
60 | 71 | }
|
61 | 72 |
|
62 |
| - mongoc_uri_destroy (uri); |
| 73 | + sleep (10); |
| 74 | + pthread_mutex_lock (&mutex); |
| 75 | + in_shutdown = true; |
| 76 | + pthread_mutex_unlock (&mutex); |
63 | 77 |
|
64 | 78 | for (i = 0; i < 10; i++) {
|
65 |
| - pthread_join (threads [i], &ret); |
| 79 | + pthread_join (threads[i], &ret); |
66 | 80 | }
|
67 | 81 |
|
| 82 | + mongoc_client_pool_destroy (pool); |
| 83 | + mongoc_uri_destroy (uri); |
| 84 | +
|
68 | 85 | mongoc_cleanup ();
|
69 | 86 |
|
70 | 87 | return 0;
|
71 |
| -}]]></code></screen> |
| 88 | +} |
| 89 | +]]></code></screen> |
72 | 90 | </section>
|
73 | 91 |
|
74 | 92 | <links type="topic" groups="function" style="2column">
|
|
0 commit comments