| 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>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="wrapup.html" title="Chapter 6. Summary and Examples" /> |
| 12 |
<link rel="next" href="inmem_txnexample_c.html" title="In-Memory Transaction Example" /> |
| 13 |
</head> |
| 14 |
<body> |
| 15 |
<div xmlns="" class="navheader"> |
| 16 |
<div class="libver"> |
| 17 |
<p>Library Version 11.2.5.3</p> |
| 18 |
</div> |
| 19 |
<table width="100%" summary="Navigation header"> |
| 20 |
<tr> |
| 21 |
<th colspan="3" align="center">Transaction Example</th> |
| 22 |
</tr> |
| 23 |
<tr> |
| 24 |
<td width="20%" align="left"><a accesskey="p" href="wrapup.html">Prev</a> </td> |
| 25 |
<th width="60%" align="center">Chapter 6. Summary and Examples</th> |
| 26 |
<td width="20%" align="right"> <a accesskey="n" href="inmem_txnexample_c.html">Next</a></td> |
| 27 |
</tr> |
| 28 |
</table> |
| 29 |
<hr /> |
| 30 |
</div> |
| 31 |
<div class="sect1" lang="en" xml:lang="en"> |
| 32 |
<div class="titlepage"> |
| 33 |
<div> |
| 34 |
<div> |
| 35 |
<h2 class="title" style="clear: both"><a id="txnexample_c"></a>Transaction Example</h2> |
| 36 |
</div> |
| 37 |
</div> |
| 38 |
</div> |
| 39 |
<p> |
| 40 |
The following code provides a fully functional example of a |
| 41 |
multi-threaded transactional DB application. For improved |
| 42 |
portability across platforms, this examples uses pthreads to |
| 43 |
provide threading support. |
| 44 |
</p> |
| 45 |
<p> |
| 46 |
The example opens an environment and database and then creates 5 |
| 47 |
threads, each of which writes 500 records to the database. The keys |
| 48 |
used for these writes are pre-determined strings, while the data is |
| 49 |
a random value. This means that the actual data is arbitrary and |
| 50 |
therefore uninteresting; we picked it only because it requires |
| 51 |
minimum code to implement and therefore will stay out of the way of |
| 52 |
the main points of this example. |
| 53 |
</p> |
| 54 |
<p> |
| 55 |
Each thread writes 10 records under a single transaction |
| 56 |
before committing and writing another 10 (this is repeated 50 |
| 57 |
times). At the end of each transaction, but before committing, each |
| 58 |
thread calls a function that uses a cursor to read every record in |
| 59 |
the database. We do this in order to make some points about |
| 60 |
database reads in a transactional environment. |
| 61 |
</p> |
| 62 |
<p> |
| 63 |
Of course, each writer thread performs deadlock detection as |
| 64 |
described in this manual. In addition, normal recovery is performed |
| 65 |
when the environment is opened. |
| 66 |
</p> |
| 67 |
<p> |
| 68 |
We start with our normal <code class="literal">include</code> directives: |
| 69 |
</p> |
| 70 |
<pre class="programlisting">/* File: txn_guide.c */ |
| 71 |
|
| 72 |
/* We assume an ANSI-compatible compiler */ |
| 73 |
#include <stdio.h> |
| 74 |
#include <stdlib.h> |
| 75 |
#include <string.h> |
| 76 |
#include <pthread.h> |
| 77 |
#include <db.h> |
| 78 |
|
| 79 |
#ifdef _WIN32 |
| 80 |
extern int getopt(int, char * const *, const char *); |
| 81 |
#else |
| 82 |
#include <unistd.h> |
| 83 |
#endif </pre> |
| 84 |
<p> |
| 85 |
We also need a directive that we use to identify how many threads we |
| 86 |
want our program to create: |
| 87 |
</p> |
| 88 |
<pre class="programlisting">/* Run 5 writers threads at a time. */ |
| 89 |
#define NUMWRITERS 5 </pre> |
| 90 |
<p> |
| 91 |
Next we declare a couple of global |
| 92 |
variables (used by our threads), and we provide our forward |
| 93 |
declarations for the functions used by this example. |
| 94 |
</p> |
| 95 |
<pre class="programlisting">/* |
| 96 |
* Printing of pthread_t is implementation-specific, so we |
| 97 |
* create our own thread IDs for reporting purposes. |
| 98 |
*/ |
| 99 |
int global_thread_num; |
| 100 |
pthread_mutex_t thread_num_lock; |
| 101 |
|
| 102 |
/* Forward declarations */ |
| 103 |
int count_records(DB *, DB_TXN *); |
| 104 |
int open_db(DB **, const char *, const char *, DB_ENV *, u_int32_t); |
| 105 |
int usage(void); |
| 106 |
void *writer_thread(void *); </pre> |
| 107 |
<p> |
| 108 |
We now implement our usage function, which identifies our only command line |
| 109 |
parameter: |
| 110 |
</p> |
| 111 |
<pre class="programlisting">/* Usage function */ |
| 112 |
int |
| 113 |
usage() |
| 114 |
{ |
| 115 |
fprintf(stderr, " [-h <database_home_directory>]\n"); |
| 116 |
return (EXIT_FAILURE); |
| 117 |
} </pre> |
| 118 |
<p> |
| 119 |
With that, we have finished up our program's housekeeping, and we can |
| 120 |
now move on to the main part of our program. As usual, we begin with |
| 121 |
<code class="function">main()</code>. First we declare all our variables, and |
| 122 |
then we initialize our DB handles. |
| 123 |
</p> |
| 124 |
<pre class="programlisting">int |
| 125 |
main(int argc, char *argv[]) |
| 126 |
{ |
| 127 |
/* Initialize our handles */ |
| 128 |
DB *dbp = NULL; |
| 129 |
DB_ENV *envp = NULL; |
| 130 |
|
| 131 |
pthread_t writer_threads[NUMWRITERS]; |
| 132 |
int ch, i, ret, ret_t; |
| 133 |
u_int32_t env_flags; |
| 134 |
char *db_home_dir; |
| 135 |
/* Application name */ |
| 136 |
const char *prog_name = "txn_guide"; |
| 137 |
/* Database file name */ |
| 138 |
const char *file_name = "mydb.db"; </pre> |
| 139 |
<p> |
| 140 |
Now we need to parse our command line. In this case, all we want is to |
| 141 |
know where our environment directory is. If the <code class="literal">-h</code> |
| 142 |
option is not provided when this example is run, the current working |
| 143 |
directory is used instead. |
| 144 |
</p> |
| 145 |
<pre class="programlisting"> /* Parse the command line arguments */ |
| 146 |
#ifdef _WIN32 |
| 147 |
db_home_dir = ".\\"; |
| 148 |
#else |
| 149 |
db_home_dir = "./"; |
| 150 |
#endif |
| 151 |
while ((ch = getopt(argc, argv, "h:")) != EOF) |
| 152 |
switch (ch) { |
| 153 |
case 'h': |
| 154 |
db_home_dir = optarg; |
| 155 |
break; |
| 156 |
case '?': |
| 157 |
default: |
| 158 |
return (usage()); |
| 159 |
} </pre> |
| 160 |
<p> |
| 161 |
Next we create our database handle, and we define our environment open flags. |
| 162 |
There are a few things to notice here: |
| 163 |
</p> |
| 164 |
<div class="itemizedlist"> |
| 165 |
<ul type="disc"> |
| 166 |
<li> |
| 167 |
<p> |
| 168 |
We specify <code class="literal">DB_RECOVER</code>, which means that normal |
| 169 |
recovery is run every time we start the application. This is |
| 170 |
highly desirable and recommended for most |
| 171 |
applications. |
| 172 |
</p> |
| 173 |
</li> |
| 174 |
<li> |
| 175 |
<p> |
| 176 |
We also specify <code class="literal">DB_THREAD</code>, which means our |
| 177 |
environment handle will be free-threaded. This is very |
| 178 |
important because we will be sharing the environment handle |
| 179 |
across threads. |
| 180 |
</p> |
| 181 |
</li> |
| 182 |
</ul> |
| 183 |
</div> |
| 184 |
<pre class="programlisting"> /* Create the environment */ |
| 185 |
ret = db_env_create(&envp, 0); |
| 186 |
if (ret != 0) { |
| 187 |
fprintf(stderr, "Error creating environment handle: %s\n", |
| 188 |
db_strerror(ret)); |
| 189 |
goto err; |
| 190 |
} |
| 191 |
|
| 192 |
env_flags = |
| 193 |
DB_CREATE | /* Create the environment if it does not exist */ |
| 194 |
DB_RECOVER | /* Run normal recovery. */ |
| 195 |
DB_INIT_LOCK | /* Initialize the locking subsystem */ |
| 196 |
DB_INIT_LOG | /* Initialize the logging subsystem */ |
| 197 |
DB_INIT_TXN | /* Initialize the transactional subsystem. This |
| 198 |
* also turns on logging. */ |
| 199 |
DB_INIT_MPOOL | /* Initialize the memory pool (in-memory cache) */ |
| 200 |
DB_THREAD; /* Cause the environment to be free-threaded */ </pre> |
| 201 |
<p> |
| 202 |
Now we configure how we want deadlock detection performed. In our case, we will cause DB to perform deadlock |
| 203 |
detection by walking its internal lock tables looking for a block every time a lock is requested. Further, in the |
| 204 |
event of a deadlock, the thread that holds the youngest lock will receive the deadlock notification. |
| 205 |
</p> |
| 206 |
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"> |
| 207 |
<h3 class="title">Note</h3> |
| 208 |
<p> |
| 209 |
You will notice that every database operation checks the |
| 210 |
operation's status return code, and if an error |
| 211 |
(non-zero) status is returned, we log the error and then go to |
| 212 |
a <code class="literal">err</code> label in our program. Unlike |
| 213 |
object-oriented programs such as C++ or Java, we do not have |
| 214 |
<code class="literal">try</code> blocks in C. Therefore, this is the best |
| 215 |
way for us to implement cascading error handling for this |
| 216 |
example. |
| 217 |
</p> |
| 218 |
</div> |
| 219 |
<pre class="programlisting"> /* |
| 220 |
* Indicate that we want db to perform lock detection internally. |
| 221 |
* Also indicate that the transaction with the fewest number of |
| 222 |
* write locks will receive the deadlock notification in |
| 223 |
* the event of a deadlock. |
| 224 |
*/ |
| 225 |
ret = envp->set_lk_detect(envp, DB_LOCK_MINWRITE); |
| 226 |
if (ret != 0) { |
| 227 |
fprintf(stderr, "Error setting lock detect: %s\n", |
| 228 |
db_strerror(ret)); |
| 229 |
goto err; |
| 230 |
} </pre> |
| 231 |
<p> |
| 232 |
Now we open our environment. |
| 233 |
</p> |
| 234 |
<pre class="programlisting"> /* |
| 235 |
* If we had utility threads (for running checkpoints or |
| 236 |
* deadlock detection, for example) we would spawn those |
| 237 |
* here. However, for a simple example such as this, |
| 238 |
* that is not required. |
| 239 |
*/ |
| 240 |
|
| 241 |
/* Now actually open the environment */ |
| 242 |
ret = envp->open(envp, db_home_dir, env_flags, 0); |
| 243 |
if (ret != 0) { |
| 244 |
fprintf(stderr, "Error opening environment: %s\n", |
| 245 |
db_strerror(ret)); |
| 246 |
goto err; |
| 247 |
} </pre> |
| 248 |
<p> |
| 249 |
Now we call the function that will open our database for us. This is |
| 250 |
not very interesting, except that you will notice that we are |
| 251 |
specifying <code class="literal">DB_DUPSORT</code>. This is required purely by |
| 252 |
the data that we are writing to the database, and it is only necessary |
| 253 |
if you run the application more than once without first deleting the environment. |
| 254 |
</p> |
| 255 |
<p> |
| 256 |
Also, we do not provide any error logging here because the |
| 257 |
<code class="function">open_db()</code> function does that for us. |
| 258 |
(The implementation of <code class="function">open_db()</code> is described |
| 259 |
later in this section.) |
| 260 |
</p> |
| 261 |
<pre class="programlisting"> /* Open the database */ |
| 262 |
ret = open_db(&dbp, prog_name, file_name, envp, DB_DUPSORT); |
| 263 |
if (ret != 0) |
| 264 |
goto err; </pre> |
| 265 |
<p> |
| 266 |
Now we create our threads. In this example we are using pthreads |
| 267 |
for our threading package. A description of threading (beyond how |
| 268 |
it impacts DB usage) is beyond the scope of this manual. |
| 269 |
However, the things that we are doing here should be familiar to |
| 270 |
anyone who has prior experience with any threading package. We are |
| 271 |
simply initializing a mutex, creating our threads, and then joining |
| 272 |
our threads, which causes our program to wait until the joined |
| 273 |
threads have completed before continuing operations in the main |
| 274 |
thread. |
| 275 |
</p> |
| 276 |
<pre class="programlisting"> /* Initialize a pthread mutex. Used to help provide thread ids. */ |
| 277 |
(void)pthread_mutex_init(&thread_num_lock, NULL); |
| 278 |
|
| 279 |
/* Start the writer threads. */ |
| 280 |
for (i = 0; i < NUMWRITERS; i++) |
| 281 |
(void)pthread_create(&writer_threads[i], NULL, |
| 282 |
writer_thread, (void *)dbp); |
| 283 |
|
| 284 |
/* Join the writers */ |
| 285 |
for (i = 0; i < NUMWRITERS; i++) |
| 286 |
(void)pthread_join(writer_threads[i], NULL); </pre> |
| 287 |
<p> |
| 288 |
Finally, to wrap up <code class="function">main()</code>, we close out our |
| 289 |
database and environment handle, as is normal for any DB |
| 290 |
application. Notice that this is where our <code class="literal">err</code> |
| 291 |
label is placed in our application. If any database operation prior |
| 292 |
to this point in the program returns an error status, the program |
| 293 |
simply jumps to this point and closes our handles if necessary |
| 294 |
before exiting the application completely. |
| 295 |
</p> |
| 296 |
<pre class="programlisting">err: |
| 297 |
/* Close our database handle, if it was opened. */ |
| 298 |
if (dbp != NULL) { |
| 299 |
ret_t = dbp->close(dbp, 0); |
| 300 |
if (ret_t != 0) { |
| 301 |
fprintf(stderr, "%s database close failed: %s\n", |
| 302 |
file_name, db_strerror(ret_t)); |
| 303 |
ret = ret_t; |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
/* Close our environment, if it was opened. */ |
| 308 |
if (envp != NULL) { |
| 309 |
ret_t = envp->close(envp, 0); |
| 310 |
if (ret_t != 0) { |
| 311 |
fprintf(stderr, "environment close failed: %s\n", |
| 312 |
db_strerror(ret_t)); |
| 313 |
ret = ret_t; |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
/* Final status message and return. */ |
| 318 |
printf("I'm all done.\n"); |
| 319 |
return (ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE); |
| 320 |
} </pre> |
| 321 |
<p> |
| 322 |
Now that we have completed <code class="function">main()</code>, we need to |
| 323 |
implement the function that our writer threads will actually run. This |
| 324 |
is where the bulk of our transactional code resides. |
| 325 |
</p> |
| 326 |
<p> |
| 327 |
We start as usual with variable declarations and initialization. |
| 328 |
</p> |
| 329 |
<pre class="programlisting">/* |
| 330 |
* A function that performs a series of writes to a |
| 331 |
* Berkeley DB database. The information written |
| 332 |
* to the database is largely nonsensical, but the |
| 333 |
* mechanisms of transactional commit/abort and |
| 334 |
* deadlock detection are illustrated here. |
| 335 |
*/ |
| 336 |
void * |
| 337 |
writer_thread(void *args) |
| 338 |
{ |
| 339 |
DBT key, value; |
| 340 |
DB_TXN *txn; |
| 341 |
int i, j, payload, ret, thread_num; |
| 342 |
int retry_count, max_retries = 20; /* Max retry on a deadlock */ |
| 343 |
char *key_strings[] = {"key 1", "key 2", "key 3", "key 4", |
| 344 |
"key 5", "key 6", "key 7", "key 8", |
| 345 |
"key 9", "key 10"}; |
| 346 |
|
| 347 |
DB *dbp = (DB *)args; |
| 348 |
DB_ENV *envp = dbp->get_env(dbp); </pre> |
| 349 |
<p> |
| 350 |
Now we want a thread number for reporting purposes. It is possible to |
| 351 |
use the <code class="literal">pthread_t</code> value directly for this purpose, |
| 352 |
but how that is done unfortunately differs depending |
| 353 |
on the pthread implementation you are using. So instead we use a |
| 354 |
mutex-protected global variable to obtain a simple integer for |
| 355 |
our reporting purposes. |
| 356 |
</p> |
| 357 |
<p> |
| 358 |
Note that we are also use this thread id for initializing a random number generator, which we do here. |
| 359 |
We use this random number generator for data generation. |
| 360 |
</p> |
| 361 |
<pre class="programlisting"> /* Get the thread number */ |
| 362 |
(void)pthread_mutex_lock(&thread_num_lock); |
| 363 |
global_thread_num++; |
| 364 |
thread_num = global_thread_num; |
| 365 |
(void)pthread_mutex_unlock(&thread_num_lock); |
| 366 |
|
| 367 |
/* Initialize the random number generator */ |
| 368 |
srand((u_int)pthread_self()); </pre> |
| 369 |
<p> |
| 370 |
Now we begin the loop that we use to write data to the database. |
| 371 |
<span> |
| 372 |
Notice that at the beginning of the top loop, we begin a new |
| 373 |
transaction. |
| 374 |
</span> |
| 375 |
|
| 376 |
|
| 377 |
We will actually use 50 transactions per writer |
| 378 |
thread, although we will only ever have one active transaction per |
| 379 |
thread at a time. Within each transaction, we will perform 10 |
| 380 |
database writes. |
| 381 |
</p> |
| 382 |
<p> |
| 383 |
By combining multiple writes together under a single transaction, |
| 384 |
we increase the likelihood that a deadlock will occur. Normally, |
| 385 |
you want to reduce the potential for a deadlock and in this case |
| 386 |
the way to do that is to perform a single write per transaction. |
| 387 |
To avoid deadlocks, we could be using auto commit to |
| 388 |
write to our database for this workload. |
| 389 |
</p> |
| 390 |
<p> |
| 391 |
However, we want to show deadlock handling and by performing |
| 392 |
multiple writes per transaction we can actually observe deadlocks |
| 393 |
occurring. We also want to underscore the idea that you can |
| 394 |
combing multiple database operations together in a single atomic |
| 395 |
unit of work in order to improve the efficiency of your writes. |
| 396 |
</p> |
| 397 |
<p> |
| 398 |
Finally, on an issue of style, you will notice the |
| 399 |
<code class="literal">retry</code> label that we place immediately before our |
| 400 |
transaction begin code. We use this to loop in the event that a |
| 401 |
deadlock is detected and the write operation has to be performed. A |
| 402 |
great many people dislike looping with <code class="literal">goto</code> |
| 403 |
statements, and we certainly could have written this code to avoid |
| 404 |
it. However, we find that using the |
| 405 |
<code class="literal">goto</code> in this case greatly helps to clarify the |
| 406 |
code, so we ignore the bias against <code class="literal">goto</code> |
| 407 |
programming in order to clearly support looping in the event of |
| 408 |
what is really an error condition. |
| 409 |
</p> |
| 410 |
<pre class="programlisting"> /* Write 50 times and then quit */ |
| 411 |
for (i = 0; i < 50; i++) { |
| 412 |
retry_count = 0; /* Used for deadlock retries */ |
| 413 |
|
| 414 |
retry: |
| 415 |
/* Begin our transaction. */ |
| 416 |
ret = envp->txn_begin(envp, NULL, &txn, 0); |
| 417 |
if (ret != 0) { |
| 418 |
envp->err(envp, ret, "txn_begin failed"); |
| 419 |
return ((void *)EXIT_FAILURE); |
| 420 |
} </pre> |
| 421 |
<p> |
| 422 |
Now we begin the inner loop that we use to actually |
| 423 |
perform the write. Notice that we use a <code class="literal">case</code> |
| 424 |
statement to examine the return code from the database put. |
| 425 |
This case statement is what we use to determine whether we need |
| 426 |
to abort (or abort/retry in the case of a deadlock) our current |
| 427 |
transaction. |
| 428 |
</p> |
| 429 |
<pre class="programlisting"> for (j = 0; j < 10; j++) { |
| 430 |
/* Set up our key and values DBTs */ |
| 431 |
memset(&key, 0, sizeof(DBT)); |
| 432 |
key.data = key_strings[j]; |
| 433 |
key.size = (strlen(key_strings[j]) + 1) * sizeof(char); |
| 434 |
|
| 435 |
memset(&value, 0, sizeof(DBT)); |
| 436 |
payload = rand() + i; |
| 437 |
value.data = &payload; |
| 438 |
value.size = sizeof(int); |
| 439 |
|
| 440 |
/* Perform the database put. */ |
| 441 |
switch (ret = dbp->put(dbp, txn, &key, &value, 0)) { |
| 442 |
case 0: |
| 443 |
break; |
| 444 |
/* |
| 445 |
* Our database is configured for sorted duplicates, |
| 446 |
* so there is a potential for a KEYEXIST error return. |
| 447 |
* If we get one, simply ignore it and continue on. |
| 448 |
* |
| 449 |
* Note that you will see KEYEXIST errors only after you |
| 450 |
* have run this program at least once. |
| 451 |
*/ |
| 452 |
case DB_KEYEXIST: |
| 453 |
printf("Got keyexists.\n"); |
| 454 |
break; |
| 455 |
/* |
| 456 |
* Here's where we perform deadlock detection. If |
| 457 |
* DB_LOCK_DEADLOCK is returned by the put operation, |
| 458 |
* then this thread has been chosen to break a deadlock. |
| 459 |
* It must abort its operation, and optionally retry the |
| 460 |
* put. |
| 461 |
*/ |
| 462 |
case DB_LOCK_DEADLOCK: |
| 463 |
/* |
| 464 |
* First thing we MUST do is abort the |
| 465 |
* transaction. |
| 466 |
*/ |
| 467 |
(void)txn->abort(txn); |
| 468 |
/* |
| 469 |
* Now we decide if we want to retry the operation. |
| 470 |
* If we have retried less than max_retries, |
| 471 |
* increment the retry count and goto retry. |
| 472 |
*/ |
| 473 |
if (retry_count < max_retries) { |
| 474 |
printf("Writer %i: Got DB_LOCK_DEADLOCK.\n", |
| 475 |
thread_num); |
| 476 |
printf("Writer %i: Retrying write operation.\n", |
| 477 |
thread_num); |
| 478 |
retry_count++; |
| 479 |
goto retry; |
| 480 |
} |
| 481 |
/* |
| 482 |
* Otherwise, just give up. |
| 483 |
*/ |
| 484 |
printf("Writer %i: ", thread_num); |
| 485 |
printf("Got DB_LOCK_DEADLOCK and out of retries.\n"); |
| 486 |
printf("Writer %i: Giving up.\n", thread_num); |
| 487 |
return ((void *)EXIT_FAILURE); |
| 488 |
/* |
| 489 |
* If a generic error occurs, we simply abort the |
| 490 |
* transaction and exit the thread completely. |
| 491 |
*/ |
| 492 |
default: |
| 493 |
envp->err(envp, ret, "db put failed"); |
| 494 |
ret = txn->abort(txn); |
| 495 |
if (ret != 0) |
| 496 |
envp->err(envp, ret, "txn abort failed"); |
| 497 |
return ((void *)EXIT_FAILURE); |
| 498 |
} /** End case statement **/ |
| 499 |
|
| 500 |
} /** End for loop **/ </pre> |
| 501 |
<p> |
| 502 |
Having completed the inner database write loop, we could simply |
| 503 |
commit the transaction and continue on to the next block of 10 |
| 504 |
writes. However, we want to first illustrate a few points about |
| 505 |
transactional processing so instead we call our |
| 506 |
<code class="function">count_records()</code> |
| 507 |
|
| 508 |
|
| 509 |
function before calling the transaction |
| 510 |
commit. |
| 511 |
<code class="function">count_records()</code> |
| 512 |
|
| 513 |
uses a cursor to read every |
| 514 |
record in the database and return a count of the number of records |
| 515 |
that it found. |
| 516 |
</p> |
| 517 |
<pre class="programlisting"> /* |
| 518 |
* print the number of records found in the database. |
| 519 |
* See count_records() for usage information. |
| 520 |
*/ |
| 521 |
printf("Thread %i. Record count: %i\n", thread_num, |
| 522 |
count_records(dbp, NULL)); |
| 523 |
|
| 524 |
/* |
| 525 |
* If all goes well, we can commit the transaction and |
| 526 |
* loop to the next transaction. |
| 527 |
*/ |
| 528 |
ret = txn->commit(txn, 0); |
| 529 |
if (ret != 0) { |
| 530 |
envp->err(envp, ret, "txn commit failed"); |
| 531 |
return ((void *)EXIT_FAILURE); |
| 532 |
} |
| 533 |
} |
| 534 |
return ((void *)EXIT_SUCCESS); |
| 535 |
} </pre> |
| 536 |
<p> |
| 537 |
|
| 538 |
If you look at the |
| 539 |
<code class="function">count_records()</code> |
| 540 |
|
| 541 |
function prototype at the beginning of this example, you will see that the |
| 542 |
function's second parameter takes a transaction handle. However, |
| 543 |
our usage of the function here does not pass a transaction handle |
| 544 |
through to the function. |
| 545 |
</p> |
| 546 |
<p> |
| 547 |
|
| 548 |
Because |
| 549 |
<code class="function">count_records()</code> |
| 550 |
|
| 551 |
reads every record in the database, if used incorrectly the thread |
| 552 |
will self-deadlock. The writer thread has just written 500 records |
| 553 |
to the database, but because the transaction used for that write |
| 554 |
has not yet been committed, each of those 500 records are still |
| 555 |
locked by the thread's transaction. If we then simply run a |
| 556 |
non-transactional cursor over the database from within the same |
| 557 |
thread that has locked those 500 records, the cursor will |
| 558 |
block when it tries to read one of those transactional |
| 559 |
protected records. The thread immediately stops operation at that |
| 560 |
point while the cursor waits for the read lock it has |
| 561 |
requested. Because that read lock will never be released (the thread |
| 562 |
can never make any forward progress), this represents a |
| 563 |
self-deadlock for the the thread. |
| 564 |
</p> |
| 565 |
<p> |
| 566 |
There are three ways to prevent this self-deadlock: |
| 567 |
</p> |
| 568 |
<div class="orderedlist"> |
| 569 |
<ol type="1"> |
| 570 |
<li> |
| 571 |
<p> |
| 572 |
We can move the call to |
| 573 |
<code class="function">count_records()</code> |
| 574 |
|
| 575 |
to a point after the thread's transaction has committed. |
| 576 |
</p> |
| 577 |
</li> |
| 578 |
<li> |
| 579 |
<p> |
| 580 |
We can allow |
| 581 |
<code class="function">count_records()</code> |
| 582 |
|
| 583 |
to operate under the same transaction as all of the writes |
| 584 |
were performed (this is what the transaction parameter for |
| 585 |
the function is for). |
| 586 |
</p> |
| 587 |
</li> |
| 588 |
<li> |
| 589 |
<p> |
| 590 |
We can reduce our isolation guarantee for the application |
| 591 |
by allowing uncommitted reads. |
| 592 |
</p> |
| 593 |
</li> |
| 594 |
</ol> |
| 595 |
</div> |
| 596 |
<p> |
| 597 |
For this example, we choose to use option 3 (uncommitted reads) to avoid |
| 598 |
the deadlock. This means that we have to open our database such |
| 599 |
that it supports uncommitted reads, and we have to open our cursor handle |
| 600 |
so that it knows to perform uncommitted reads. |
| 601 |
</p> |
| 602 |
<p> |
| 603 |
Note that in <a class="xref" href="inmem_txnexample_c.html" title="In-Memory Transaction Example">In-Memory Transaction Example</a>, |
| 604 |
we simply perform the cursor operation using the same transaction |
| 605 |
as is used for the thread's writes. |
| 606 |
</p> |
| 607 |
<p> |
| 608 |
The following is the |
| 609 |
<code class="function">count_records()</code> |
| 610 |
|
| 611 |
implementation. There is not anything particularly interesting |
| 612 |
about this function other than specifying uncommitted reads when |
| 613 |
we open the cursor handle, but we include the function here anyway |
| 614 |
for the sake of completeness. |
| 615 |
</p> |
| 616 |
<pre class="programlisting">/* |
| 617 |
* This simply counts the number of records contained in the |
| 618 |
* database and returns the result. |
| 619 |
* |
| 620 |
* Note that this function exists only for illustrative purposes. |
| 621 |
* A more straight-forward way to count the number of records in |
| 622 |
* a database is to use DB->stat() or DB->stat_print(). |
| 623 |
*/ |
| 624 |
|
| 625 |
int |
| 626 |
count_records(DB *dbp, DB_TXN *txn) |
| 627 |
{ |
| 628 |
DBT key, value; |
| 629 |
DBC *cursorp; |
| 630 |
int count, ret; |
| 631 |
|
| 632 |
cursorp = NULL; |
| 633 |
count = 0; |
| 634 |
|
| 635 |
/* Get the cursor */ |
| 636 |
ret = dbp->cursor(dbp, txn, &cursorp, DB_READ_UNCOMMITTED); |
| 637 |
if (ret != 0) { |
| 638 |
dbp->err(dbp, ret, "count_records: cursor open failed."); |
| 639 |
goto cursor_err; |
| 640 |
} |
| 641 |
|
| 642 |
/* Get the key DBT used for the database read */ |
| 643 |
memset(&key, 0, sizeof(DBT)); |
| 644 |
memset(&value, 0, sizeof(DBT)); |
| 645 |
do { |
| 646 |
ret = cursorp->get(cursorp, &key, &value, DB_NEXT); |
| 647 |
switch (ret) { |
| 648 |
case 0: |
| 649 |
count++; |
| 650 |
break; |
| 651 |
case DB_NOTFOUND: |
| 652 |
break; |
| 653 |
default: |
| 654 |
dbp->err(dbp, ret, "Count records unspecified error"); |
| 655 |
goto cursor_err; |
| 656 |
} |
| 657 |
} while (ret == 0); |
| 658 |
|
| 659 |
cursor_err: |
| 660 |
if (cursorp != NULL) { |
| 661 |
ret = cursorp->close(cursorp); |
| 662 |
if (ret != 0) { |
| 663 |
dbp->err(dbp, ret, |
| 664 |
"count_records: cursor close failed."); |
| 665 |
} |
| 666 |
} |
| 667 |
|
| 668 |
return (count); |
| 669 |
} </pre> |
| 670 |
<p> |
| 671 |
Finally, we provide the implementation of our |
| 672 |
<code class="function">open_db()</code> |
| 673 |
|
| 674 |
function. This function should hold |
| 675 |
no surprises for you. Note, however, that we do specify uncommitted reads |
| 676 |
when we open the database. If we did not do this, then our |
| 677 |
<code class="function">count_records()</code> |
| 678 |
|
| 679 |
function would cause our |
| 680 |
thread to self-deadlock because the cursor could not be opened to |
| 681 |
support uncommitted reads (that flag on the cursor open would, in fact, |
| 682 |
be silently ignored by DB). |
| 683 |
</p> |
| 684 |
<pre class="programlisting">/* Open a Berkeley DB database */ |
| 685 |
int |
| 686 |
open_db(DB **dbpp, const char *progname, const char *file_name, |
| 687 |
DB_ENV *envp, u_int32_t extra_flags) |
| 688 |
{ |
| 689 |
int ret; |
| 690 |
u_int32_t open_flags; |
| 691 |
DB *dbp; |
| 692 |
|
| 693 |
/* Initialize the DB handle */ |
| 694 |
ret = db_create(&dbp, envp, 0); |
| 695 |
if (ret != 0) { |
| 696 |
fprintf(stderr, "%s: %s\n", progname, |
| 697 |
db_strerror(ret)); |
| 698 |
return (EXIT_FAILURE); |
| 699 |
} |
| 700 |
|
| 701 |
/* Point to the memory malloc'd by db_create() */ |
| 702 |
*dbpp = dbp; |
| 703 |
|
| 704 |
if (extra_flags != 0) { |
| 705 |
ret = dbp->set_flags(dbp, extra_flags); |
| 706 |
if (ret != 0) { |
| 707 |
dbp->err(dbp, ret, |
| 708 |
"open_db: Attempt to set extra flags failed."); |
| 709 |
return (EXIT_FAILURE); |
| 710 |
} |
| 711 |
} |
| 712 |
|
| 713 |
/* Now open the database */ |
| 714 |
open_flags = DB_CREATE | /* Allow database creation */ |
| 715 |
DB_READ_UNCOMMITTED | /* Allow uncommitted reads */ |
| 716 |
DB_AUTO_COMMIT | /* Allow auto commit */ |
| 717 |
DB_THREAD; /* Cause the database to be |
| 718 |
free-threaded */ |
| 719 |
|
| 720 |
ret = dbp->open(dbp, /* Pointer to the database */ |
| 721 |
NULL, /* Txn pointer */ |
| 722 |
file_name, /* File name */ |
| 723 |
NULL, /* Logical db name */ |
| 724 |
DB_BTREE, /* Database type (using btree) */ |
| 725 |
open_flags, /* Open flags */ |
| 726 |
0); /* File mode. Using defaults */ |
| 727 |
if (ret != 0) { |
| 728 |
dbp->err(dbp, ret, "Database '%s' open failed", |
| 729 |
file_name); |
| 730 |
return (EXIT_FAILURE); |
| 731 |
} |
| 732 |
return (EXIT_SUCCESS); |
| 733 |
} </pre> |
| 734 |
<p> |
| 735 |
This completes our transactional example. If you would like to |
| 736 |
experiment with this code, you can find the example in the following |
| 737 |
location in your DB distribution: |
| 738 |
</p> |
| 739 |
<pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_c/txn_guide</pre> |
| 740 |
</div> |
| 741 |
<div class="navfooter"> |
| 742 |
<hr /> |
| 743 |
<table width="100%" summary="Navigation footer"> |
| 744 |
<tr> |
| 745 |
<td width="40%" align="left"><a accesskey="p" href="wrapup.html">Prev</a> </td> |
| 746 |
<td width="20%" align="center"> |
| 747 |
<a accesskey="u" href="wrapup.html">Up</a> |
| 748 |
</td> |
| 749 |
<td width="40%" align="right"> <a accesskey="n" href="inmem_txnexample_c.html">Next</a></td> |
| 750 |
</tr> |
| 751 |
<tr> |
| 752 |
<td width="40%" align="left" valign="top">Chapter 6. Summary and Examples </td> |
| 753 |
<td width="20%" align="center"> |
| 754 |
<a accesskey="h" href="index.html">Home</a> |
| 755 |
</td> |
| 756 |
<td width="40%" align="right" valign="top"> In-Memory Transaction Example</td> |
| 757 |
</tr> |
| 758 |
</table> |
| 759 |
</div> |
| 760 |
</body> |
| 761 |
</html> |