Debian Codegraph @

docs/gsg_txn/C/inmem_txnexample_c.html

raw
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6 <title>In-Memory Transaction Example</title>
7 <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
8 <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
9 <link rel="start" href="index.html" title="Getting Started with Berkeley DB Transaction Processing" />
10 <link rel="up" href="wrapup.html" title="Chapter 6. Summary and Examples" />
11 <link rel="prev" href="txnexample_c.html" title="Transaction Example" />
12 </head>
13 <body>
14 <div xmlns="" class="navheader">
15 <div class="libver">
16 <p>Library Version 11.2.5.3</p>
17 </div>
18 <table width="100%" summary="Navigation header">
19 <tr>
20 <th colspan="3" align="center">In-Memory Transaction Example</th>
21 </tr>
22 <tr>
23 <td width="20%" align="left"><a accesskey="p" href="txnexample_c.html">Prev</a> </td>
24 <th width="60%" align="center">Chapter 6. Summary and Examples</th>
25 <td width="20%" align="right"> </td>
26 </tr>
27 </table>
28 <hr />
29 </div>
30 <div class="sect1" lang="en" xml:lang="en">
31 <div class="titlepage">
32 <div>
33 <div>
34 <h2 class="title" style="clear: both"><a id="inmem_txnexample_c"></a>In-Memory Transaction Example</h2>
35 </div>
36 </div>
37 </div>
38 <p>
39 DB is sometimes used for applications that simply need to cache
40 data retrieved from some other location (such as a remote database
41 server). DB is also often used in embedded systems.
42 </p>
43 <p>
44 In both cases, applications may want to use transactions for
45 atomicity, consistency, and isolation guarantees, but they may also want
46 to forgo the durability guarantee entirely. In doing so, they can keep
47 their DB environment and databases entirely in-memory so
48 as to avoid the performance impact of unneeded disk I/O.
49 </p>
50 <p>
51 To do this:
52 </p>
53 <div class="itemizedlist">
54 <ul type="disc">
55 <li>
56 <p>
57 Refrain from specifying a home directory when you open your
58 environment. The exception to this is if you are using the
59 <code class="literal">DB_CONFIG</code> configuration file — in
60 that case you must identify the environment's home
61 directory so that the configuration file can be found.
62 </p>
63 </li>
64 <li>
65 <p>
66 Configure your environment to back your regions from
67 system memory instead of the filesystem.
68 </p>
69 </li>
70 <li>
71 <p>
72 Configure your logging subsystem such that log files are kept
73 entirely in-memory.
74 </p>
75 </li>
76 <li>
77 <p>
78 Increase the size of your in-memory log buffer so that it
79 is large enough to hold the largest set of concurrent write operations.
80 </p>
81 </li>
82 <li>
83 <p>
84 Increase the size of your in-memory cache so that it can
85 hold your entire data set. You do not want your cache to
86 page to disk.
87 </p>
88 </li>
89 <li>
90 <p>
91 Do not specify a file name when you open your database(s).
92 </p>
93 </li>
94 </ul>
95 </div>
96 <p>
97 As an example, this section takes the transaction example provided
98 in <a class="xref" href="txnexample_c.html" title="Transaction Example">Transaction Example</a>
99 and it updates that example so that the environment, database, log
100 files, and regions are all kept entirely in-memory.
101 </p>
102 <p>
103 For illustration purposes, we also modify this example so that
104 uncommitted reads are no longer used to enable the
105 <code class="function">count_records()</code>
106
107 function. Instead, we simply provide a transaction handle to
108 <code class="function">count_records()</code>
109
110 so as to avoid the self-deadlock. Be aware that using a transaction handle here rather than
111 uncommitted reads will work just as well as if we had continued to use uncommitted reads. However,
112 the usage of the transaction handle here will
113 probably cause more deadlocks than using read-uncommitted does, because more locking is being performed in
114 this case.
115 </p>
116 <p>
117 To begin, we simplify the beginning of our example a bit. Because
118 we no longer need an environment home directory, we can remove all
119 the code that we used to determine path delimiters
120 and include the <code class="function">getopt</code> function. We can also
121 remove our <code class="function">usage()</code> function because we no
122 longer require any command line arguments.
123 </p>
124 <pre class="programlisting">/* File: txn_guide_inmemory.c */
125
126 /* We assume an ANSI-compatible compiler */
127 #include &lt;stdio.h&gt;
128 #include &lt;stdlib.h&gt;
129 #include &lt;string.h&gt;
130 #include &lt;pthread.h&gt;
131 #include &lt;db.h&gt;
132
133 /* Run 5 writers threads at a time. */
134 #define NUMWRITERS 5
135
136 /*
137 * Printing of pthread_t is implementation-specific, so we
138 * create our own thread IDs for reporting purposes.
139 */
140 int global_thread_num;
141 pthread_mutex_t thread_num_lock;
142
143 /* Forward declarations */
144 int count_records(DB *, DB_TXN *);
145 int open_db(DB **, const char *, const char *, DB_ENV *, u_int32_t);
146 int writer_thread(void *); </pre>
147 <p>
148 Next, in our <code class="function">main()</code>, we also eliminate some
149 variables that this example no longer needs. In particular, we are able to remove
150 the
151 <code class="literal">db_home_dir</code>
152
153 and
154 <code class="literal">file_name</code>
155
156 variables. We also remove all our <code class="function">getopt</code> code.
157 </p>
158 <pre class="programlisting">int
159 main(void)
160 {
161 /* Initialize our handles */
162 DB *dbp = NULL;
163 DB_ENV *envp = NULL;
164
165 pthread_t writer_threads[NUMWRITERS];
166 int i, ret, ret_t;
167 u_int32_t env_flags;
168
169 /* Application name */
170 const char *prog_name = "txn_guide_inmemory"; </pre>
171 <p>
172 Next we create our environment as always. However, we add
173 <code class="literal">DB_PRIVATE</code> to our environment open flags. This
174 flag causes our environment to back regions using our
175 application's heap memory rather than by using the filesystem.
176 This is the first important step to keeping our DB data
177 entirely in-memory.
178 </p>
179 <p>
180 We also remove the <code class="literal">DB_RECOVER</code> flag from the environment open flags. Because our databases,
181 logs, and regions are maintained in-memory, there will never be anything to recover.
182 </p>
183 <p>
184 Note that we show the additional code here in
185 <strong class="userinput"><code>bold.</code></strong>
186 </p>
187 <pre class="programlisting"> /* Create the environment */
188 ret = db_env_create(&amp;envp, 0);
189 if (ret != 0) {
190 fprintf(stderr, "Error creating environment handle: %s\n",
191 db_strerror(ret));
192 goto err;
193 }
194
195 env_flags =
196 DB_CREATE | /* Create the environment if it does not exist */
197 DB_INIT_LOCK | /* Initialize the locking subsystem */
198 DB_INIT_LOG | /* Initialize the logging subsystem */
199 DB_INIT_TXN | /* Initialize the transactional subsystem. This
200 * also turns on logging. */
201 DB_INIT_MPOOL | /* Initialize the memory pool (in-memory cache) */
202 <strong class="userinput"><code>DB_PRIVATE | /* Region files are not backed by the filesystem.
203 * Instead, they are backed by heap memory. */</code></strong>
204 DB_THREAD; /* Cause the environment to be free-threaded */ </pre>
205 <p>
206 Now we configure our environment to keep the log files in memory,
207 increase the log buffer size to 10 MB, and increase our in-memory
208 cache to 10 MB. These values should be more than enough for our
209 application's workload.
210 </p>
211 <pre class="programlisting">
212 <strong class="userinput">
213 <code> /* Specify in-memory logging */
214 ret = envp-&gt;log_set_config(envp, DB_LOG_IN_MEMORY, 1);
215 if (ret != 0) {
216 fprintf(stderr, "Error setting log subsystem to in-memory: %s\n",
217 db_strerror(ret));
218 goto err;
219 }
220
221 /*
222 * Specify the size of the in-memory log buffer.
223 */
224 ret = envp-&gt;set_lg_bsize(envp, 10 * 1024 * 1024);
225 if (ret != 0) {
226 fprintf(stderr, "Error increasing the log buffer size: %s\n",
227 db_strerror(ret));
228 goto err;
229 }
230
231 /*
232 * Specify the size of the in-memory cache.
233 */
234 ret = envp-&gt;set_cachesize(envp, 0,
235 10 * 1024 * 1024, 1);
236 if (ret != 0) {
237 fprintf(stderr, "Error increasing the cache size: %s\n",
238 db_strerror(ret));
239 goto err;
240 }</code>
241 </strong>
242 </pre>
243 <p>
244 Next, we open the environment and setup our lock detection. This is
245 identical to how the example previously worked, except that we do not
246 provide a location for the environment's home directory.
247 </p>
248 <pre class="programlisting"> /*
249 * Indicate that we want db to perform lock detection internally.
250 * Also indicate that the transaction with the fewest number of
251 * write locks will receive the deadlock notification in
252 * the event of a deadlock.
253 */
254 ret = envp-&gt;set_lk_detect(envp, DB_LOCK_MINWRITE);
255 if (ret != 0) {
256 fprintf(stderr, "Error setting lock detect: %s\n",
257 db_strerror(ret));
258 goto err;
259 }
260
261 /* Now actually open the environment */
262 ret = envp-&gt;open(envp, <strong class="userinput"><code>NULL</code></strong>, env_flags, 0);
263 if (ret != 0) {
264 fprintf(stderr, "Error opening environment: %s\n",
265 db_strerror(ret));
266 goto err;
267 } </pre>
268 <p>
269 When we call
270 <span><code class="function">open_db()</code>,</span>
271
272 which is what we use
273 to open our database, we no not provide a database filename for the
274 third parameter. When the filename is <code class="literal">NULL</code>, the database is not
275 backed by the filesystem.
276 </p>
277 <pre class="programlisting"> /*
278 * If we had utility threads (for running checkpoints or
279 * deadlock detection, for example) we would spawn those
280 * here. However, for a simple example such as this,
281 * that is not required.
282 */
283
284 /* Open the database */
285 ret = open_db(&amp;dbp, prog_name, <strong class="userinput"><code>NULL</code></strong>,
286 envp, DB_DUPSORT);
287 if (ret != 0)
288 goto err; </pre>
289 <p>
290 After that, our <code class="function">main()</code> function is unchanged,
291 except that when we
292 <span>close the database,</span>
293
294 we change the error message string so as to not reference the database filename.
295 </p>
296 <pre class="programlisting"> /* Initialize a pthread mutex. Used to help provide thread ids. */
297 (void)pthread_mutex_init(&amp;thread_num_lock, NULL);
298
299 /* Start the writer threads. */
300 for (i = 0; i &lt; NUMWRITERS; i++)
301 (void)pthread_create(
302 &amp;writer_threads[i], NULL, (void *)writer_thread, (void *)dbp);
303
304 /* Join the writers */
305 for (i = 0; i &lt; NUMWRITERS; i++)
306 (void)pthread_join(writer_threads[i], NULL);
307
308 err:
309 /* Close our database handle, if it was opened. */
310 if (dbp != NULL) {
311 ret_t = dbp-&gt;close(dbp, 0);
312 if (ret_t != 0) {
313 <strong class="userinput"><code>fprintf(stderr, "%s database close failed.\n",
314 db_strerror(ret_t));</code></strong>
315 ret = ret_t;
316 }
317 }
318
319 /* Close our environment, if it was opened. */
320 if (envp != NULL) {
321 ret_t = envp-&gt;close(envp, 0);
322 if (ret_t != 0) {
323 fprintf(stderr, "environment close failed: %s\n",
324 db_strerror(ret_t));
325 ret = ret_t;
326 }
327 }
328
329 /* Final status message and return. */
330 printf("I'm all done.\n");
331 return (ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
332 } </pre>
333 <p>
334 That completes <code class="function">main()</code>. The bulk of our
335 <code class="function">writer_thread()</code> function implementation is
336 unchanged from the initial transaction example, except that we no
337 longer check for <code class="literal">DB_KEYEXISTS</code> in our
338 <code class="methodname">DB-&gt;put()</code> return code. Because we are
339 configuring for a completely in-memory database, there is no
340 possibility that we can run this code against an existing database.
341 Therefore, there is no way that <code class="literal">DB_KEYEXISTS</code>
342 will be returned by <code class="methodname">DB-&gt;put()</code>.
343 </p>
344 <pre class="programlisting">/*
345 * A function that performs a series of writes to a
346 * Berkeley DB database. The information written
347 * to the database is largely nonsensical, but the
348 * mechanism of transactional commit/abort and
349 * deadlock detection is illustrated here.
350 */
351 int
352 writer_thread(void *args)
353 {
354 DBT key, value;
355 DB_TXN *txn;
356 int i, j, payload, ret, thread_num;
357 int retry_count, max_retries = 20; /* Max retry on a deadlock */
358 char *key_strings[] = {"key 1", "key 2", "key 3", "key 4",
359 "key 5", "key 6", "key 7", "key 8",
360 "key 9", "key 10"};
361
362 DB *dbp = (DB *)args;
363 DbEnv *envp = dbp-&amp;gt;get_env();
364
365 /* Get the thread number */
366 (void)pthread_mutex_lock(&amp;thread_num_lock);
367 global_thread_num++;
368 thread_num = global_thread_num;
369 (void)pthread_mutex_unlock(&amp;thread_num_lock);
370
371 /* Initialize the random number generator */
372 srand((u_int)pthread_self());
373
374 /* Write 50 times and then quit */
375 for (i = 0; i &lt; 50; i++) {
376 retry_count = 0; /* Used for deadlock retries */
377
378 retry:
379 ret = envp-&gt;txn_begin(envp, NULL, &amp;txn, 0);
380 if (ret != 0) {
381 envp-&gt;err(envp, ret, "txn_begin failed");
382 return (EXIT_FAILURE);
383 }
384 for (j = 0; j &lt; 10; j++) {
385 /* Set up our key and values DBTs */
386 memset(&amp;key, 0, sizeof(DBT));
387 key.data = key_strings[j];
388 key.size = (strlen(key_strings[j]) + 1) * sizeof(char);
389
390 memset(&amp;value, 0, sizeof(DBT));
391 payload = rand() + i;
392 value.data = &amp;payload;
393 value.size = sizeof(int);
394
395 /* Perform the database put. */
396 switch (ret = dbp-&gt;put(dbp, txn, &amp;key, &amp;value, 0)) {
397 case 0:
398 break;
399
400 /*
401 * Here's where we perform deadlock detection. If
402 * DB_LOCK_DEADLOCK is returned by the put operation,
403 * then this thread has been chosen to break a deadlock.
404 * It must abort its operation, and optionally retry the
405 * put.
406 */
407 case DB_LOCK_DEADLOCK:
408 /*
409 * First that we MUST do is abort the
410 * transaction.
411 */
412 (void)txn-&gt;abort(txn);
413 /*
414 * Now we decide if we want to retry the operation.
415 * If we have retried less than max_retries,
416 * increment the retry count and goto retry.
417 */
418 if (retry_count &lt; max_retries) {
419 printf("Writer %i: Got DB_LOCK_DEADLOCK.\n",
420 thread_num);
421 printf("Writer %i: Retrying write operation.\n",
422 thread_num);
423 retry_count++;
424 goto retry;
425 }
426 /*
427 * Otherwise, just give up.
428 */
429 printf("Writer %i: ", thread_num);
430 printf("Got DB_LOCK_DEADLOCK and out of retries.\n");
431 printf("Writer %i: Giving up.\n", thread_num);
432 return (EXIT_FAILURE);
433 /*
434 * If a generic error occurs, we simply abort the
435 * transaction and exit the thread completely.
436 */
437 default:
438 envp-&gt;err(envp, ret, "db put failed");
439 ret = txn-&gt;abort(txn);
440 if (ret != 0)
441 envp-&gt;err(envp, ret, "txn abort failed");
442 return (EXIT_FAILURE);
443 } /** End case statement **/
444
445 } /** End for loop **/ </pre>
446 <p>
447 The only other change to <code class="function">writer_thread()</code>
448 is that we pass <code class="function">count_records()</code> a
449 transaction handle, rather than configuring our entire
450 application for uncommitted reads. Both mechanisms work well-enough
451 for preventing a self-deadlock. However, the individual count
452 in this example will tend to be lower than the counts seen in
453 the previous transaction example, because
454 <code class="function">count_records()</code> can no longer see records
455 created but not yet committed by other threads.
456 </p>
457 <pre class="programlisting"> /*
458 * print the number of records found in the database.
459 * See count_records() for usage information.
460 */
461 printf("Thread %i. Record count: %i\n", thread_num,
462 count_records(dbp, <strong class="userinput"><code>txn</code></strong>));
463
464 /*
465 * If all goes well, we can commit the transaction and
466 * loop to the next transaction.
467 */
468 ret = txn-&gt;commit(txn, 0);
469 if (ret != 0) {
470 envp-&gt;err(envp, ret, "txn commit failed");
471 return (EXIT_FAILURE);
472 }
473 }
474 return (EXIT_SUCCESS);
475 } </pre>
476 <p>
477 Next we update
478 <span><code class="function">count_records()</code>.</span>
479
480 The only difference
481 here is that we no longer specify <code class="literal">DB_READ_UNCOMMITTED</code> when
482 we open our cursor. Note that even this minor change is not required.
483 If we do not configure our database to support uncommitted reads,
484 <code class="literal">DB_READ_UNCOMMITTED</code> on the cursor open will be silently
485 ignored. However, we remove the flag anyway from the cursor open so as to
486 avoid confusion.
487 </p>
488 <pre class="programlisting">int
489 count_records(DB *dbp, DB_TXN *txn)
490 {
491 DBT key, value;
492 DBC *cursorp;
493 int count, ret;
494
495 cursorp = NULL;
496 count = 0;
497
498 /* Get the cursor */
499 ret = dbp-&gt;cursor(dbp, txn, &amp;cursorp, <strong class="userinput"><code>0</code></strong>);
500 if (ret != 0) {
501 dbp-&gt;err(dbp, ret, "count_records: cursor open failed.");
502 goto cursor_err;
503 }
504
505 /* Get the key DBT used for the database read */
506 memset(&amp;key, 0, sizeof(DBT));
507 memset(&amp;value, 0, sizeof(DBT));
508 do {
509 ret = cursorp-&gt;get(cursorp, &amp;key, &amp;value, DB_NEXT);
510 switch (ret) {
511 case 0:
512 count++;
513 break;
514 case DB_NOTFOUND:
515 break;
516 default:
517 dbp-&gt;err(dbp, ret,
518 "Count records unspecified error");
519 goto cursor_err;
520 }
521 } while (ret == 0);
522
523 cursor_err:
524 if (cursorp != NULL) {
525 ret = cursorp-&gt;close(cursorp);
526 if (ret != 0) {
527 dbp-&gt;err(dbp, ret,
528 "count_records: cursor close failed.");
529 }
530 }
531
532 return (count);
533 }</pre>
534 <p>
535 Finally, we update
536 <span><code class="function">open_db()</code>.</span>
537
538 This involves
539 removing <code class="literal">DB_READ_UNCOMMITTED</code> from the
540 open flags.
541
542 <span>We are also careful to change our database open error
543 message to no longer use the <code class="literal">file_name</code>
544 variable because that value will always be <code class="literal">NULL</code> for this example.</span>
545 </p>
546 <pre class="programlisting">/* Open a Berkeley DB database */
547 int
548 open_db(DB **dbpp, const char *progname, const char *file_name,
549 DB_ENV *envp, u_int32_t extra_flags)
550 {
551 int ret;
552 u_int32_t open_flags;
553 DB *dbp;
554
555 /* Initialize the DB handle */
556 ret = db_create(&amp;dbp, envp, 0);
557 if (ret != 0) {
558 fprintf(stderr, "%s: %s\n", progname,
559 db_strerror(ret));
560 return (EXIT_FAILURE);
561 }
562
563 /* Point to the memory malloc'd by db_create() */
564 *dbpp = dbp;
565
566 if (extra_flags != 0) {
567 ret = dbp-&gt;set_flags(dbp, extra_flags);
568 if (ret != 0) {
569 dbp-&gt;err(dbp, ret,
570 "open_db: Attempt to set extra flags failed.");
571 return (EXIT_FAILURE);
572 }
573 }
574
575 /* Now open the database */
576 <strong class="userinput"><code>open_flags = DB_CREATE | /* Allow database creation */
577 DB_THREAD |
578 DB_AUTO_COMMIT; /* Allow auto commit */</code></strong>
579
580 ret = dbp-&gt;open(dbp, /* Pointer to the database */
581 NULL, /* Txn pointer */
582 file_name, /* File name */
583 NULL, /* Logical db name */
584 DB_BTREE, /* Database type (using btree) */
585 open_flags, /* Open flags */
586 0); /* File mode. Using defaults */
587 if (ret != 0) {
588 <strong class="userinput"><code>dbp-&gt;err(dbp, ret, "Database open failed");
589 return (EXIT_FAILURE);</code></strong>
590 }
591 return (EXIT_SUCCESS);
592 } </pre>
593 <p>
594 This completes our in-memory transactional example. If you would like to
595 experiment with this code, you can find the example in the following
596 location in your DB distribution:
597 </p>
598 <pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_c/txn_guide</pre>
599 </div>
600 <div class="navfooter">
601 <hr />
602 <table width="100%" summary="Navigation footer">
603 <tr>
604 <td width="40%" align="left"><a accesskey="p" href="txnexample_c.html">Prev</a> </td>
605 <td width="20%" align="center">
606 <a accesskey="u" href="wrapup.html">Up</a>
607 </td>
608 <td width="40%" align="right"> </td>
609 </tr>
610 <tr>
611 <td width="40%" align="left" valign="top">Transaction Example </td>
612 <td width="20%" align="center">
613 <a accesskey="h" href="index.html">Home</a>
614 </td>
615 <td width="40%" align="right" valign="top"> </td>
616 </tr>
617 </table>
618 </div>
619 </body>
620 </html>