| 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 TxnGuide.cpp |
| 71 |
|
| 72 |
// We assume an ANSI-compatible compiler |
| 73 |
#include <db_cxx.h> |
| 74 |
#include <pthread.h> |
| 75 |
#include <iostream> |
| 76 |
|
| 77 |
#ifdef _WIN32 |
| 78 |
extern int getopt(int, char * const *, const char *); |
| 79 |
#else |
| 80 |
#include <unistd.h> |
| 81 |
#endif </pre> |
| 82 |
<p> |
| 83 |
We also need a directive that we use to identify how many threads we |
| 84 |
want our program to create: |
| 85 |
</p> |
| 86 |
<pre class="programlisting">// Run 5 writers threads at a time. |
| 87 |
#define NUMWRITERS 5 </pre> |
| 88 |
<p> |
| 89 |
Next we declare a couple of global |
| 90 |
variables (used by our threads), and we provide our forward |
| 91 |
declarations for the functions used by this example. |
| 92 |
</p> |
| 93 |
<pre class="programlisting">// Printing of pthread_t is implementation-specific, so we |
| 94 |
// create our own thread IDs for reporting purposes. |
| 95 |
int global_thread_num; |
| 96 |
pthread_mutex_t thread_num_lock; |
| 97 |
|
| 98 |
// Forward declarations |
| 99 |
int countRecords(Db *, DbTxn *); |
| 100 |
int openDb(Db **, const char *, const char *, DbEnv *, u_int32_t); |
| 101 |
int usage(void); |
| 102 |
void *writerThread(void *); </pre> |
| 103 |
<p> |
| 104 |
We now implement our usage function, which identifies our only command line |
| 105 |
parameter: |
| 106 |
</p> |
| 107 |
<pre class="programlisting">// Usage function |
| 108 |
int |
| 109 |
usage() |
| 110 |
{ |
| 111 |
std::cerr << " [-h <database_home_directory>]" << std::endl; |
| 112 |
return (EXIT_FAILURE); |
| 113 |
} </pre> |
| 114 |
<p> |
| 115 |
With that, we have finished up our program's housekeeping, and we can |
| 116 |
now move on to the main part of our program. As usual, we begin with |
| 117 |
<code class="function">main()</code>. First we declare all our variables, and |
| 118 |
then we initialize our DB handles. |
| 119 |
</p> |
| 120 |
<pre class="programlisting">int |
| 121 |
main(int argc, char *argv[]) |
| 122 |
{ |
| 123 |
// Initialize our handles |
| 124 |
Db *dbp = NULL; |
| 125 |
DbEnv *envp = NULL; |
| 126 |
|
| 127 |
pthread_t writerThreads[NUMWRITERS]; |
| 128 |
int ch, i; |
| 129 |
u_int32_t envFlags; |
| 130 |
char *dbHomeDir; |
| 131 |
|
| 132 |
// Application name |
| 133 |
const char *progName = "TxnGuide"; |
| 134 |
|
| 135 |
// Database file name |
| 136 |
const char *fileName = "mydb.db"; </pre> |
| 137 |
<p> |
| 138 |
Now we need to parse our command line. In this case, all we want is to |
| 139 |
know where our environment directory is. If the <code class="literal">-h</code> |
| 140 |
option is not provided when this example is run, the current working |
| 141 |
directory is used instead. |
| 142 |
</p> |
| 143 |
<pre class="programlisting"> // Parse the command line arguments |
| 144 |
#ifdef _WIN32 |
| 145 |
dbHomeDir = ".\\"; |
| 146 |
#else |
| 147 |
dbHomeDir = "./"; |
| 148 |
#endif |
| 149 |
while ((ch = getopt(argc, argv, "h:")) != EOF) |
| 150 |
switch (ch) { |
| 151 |
case 'h': |
| 152 |
dbHomeDir = optarg; |
| 153 |
break; |
| 154 |
case '?': |
| 155 |
default: |
| 156 |
return (usage()); |
| 157 |
} </pre> |
| 158 |
<p> |
| 159 |
Next we create our database handle, and we define our environment open flags. |
| 160 |
There are a few things to notice here: |
| 161 |
</p> |
| 162 |
<div class="itemizedlist"> |
| 163 |
<ul type="disc"> |
| 164 |
<li> |
| 165 |
<p> |
| 166 |
We specify <code class="literal">DB_RECOVER</code>, which means that normal |
| 167 |
recovery is run every time we start the application. This is |
| 168 |
highly desirable and recommended for most |
| 169 |
applications. |
| 170 |
</p> |
| 171 |
</li> |
| 172 |
<li> |
| 173 |
<p> |
| 174 |
We also specify <code class="literal">DB_THREAD</code>, which means our |
| 175 |
environment handle will be free-threaded. This is very |
| 176 |
important because we will be sharing the environment handle |
| 177 |
across threads. |
| 178 |
</p> |
| 179 |
</li> |
| 180 |
</ul> |
| 181 |
</div> |
| 182 |
<pre class="programlisting"> // Env open flags |
| 183 |
envFlags = |
| 184 |
DB_CREATE | // Create the environment if it does not exist |
| 185 |
DB_RECOVER | // Run normal recovery. |
| 186 |
DB_INIT_LOCK | // Initialize the locking subsystem |
| 187 |
DB_INIT_LOG | // Initialize the logging subsystem |
| 188 |
DB_INIT_TXN | // Initialize the transactional subsystem. This |
| 189 |
// also turns on logging. |
| 190 |
DB_INIT_MPOOL | // Initialize the memory pool (in-memory cache) |
| 191 |
DB_THREAD; // Cause the environment to be free-threaded |
| 192 |
|
| 193 |
try { |
| 194 |
// Create and open the environment |
| 195 |
envp = new DbEnv(0); </pre> |
| 196 |
<p> |
| 197 |
Now we configure how we want deadlock detection performed. In our case, we will cause DB to perform deadlock |
| 198 |
detection by walking its internal lock tables looking for a block every time a lock is requested. Further, in the |
| 199 |
event of a deadlock, the thread that holds the youngest lock will receive the deadlock notification. |
| 200 |
</p> |
| 201 |
<pre class="programlisting"> // Indicate that we want db to internally perform deadlock |
| 202 |
// detection. Also indicate that the transaction with |
| 203 |
// the fewest number of write locks will receive the |
| 204 |
// deadlock notification in the event of a deadlock. |
| 205 |
envp->set_lk_detect(DB_LOCK_MINWRITE); </pre> |
| 206 |
<p> |
| 207 |
Now we open our environment. |
| 208 |
</p> |
| 209 |
<pre class="programlisting"> // If we had utility threads (for running checkpoints or |
| 210 |
// deadlock detection, for example) we would spawn those |
| 211 |
// here. However, for a simple example such as this, |
| 212 |
// that is not required. |
| 213 |
|
| 214 |
envp->open(dbHomeDir, envFlags, 0); </pre> |
| 215 |
<p> |
| 216 |
Now we call the function that will open our database for us. This is |
| 217 |
not very interesting, except that you will notice that we are |
| 218 |
specifying <code class="literal">DB_DUPSORT</code>. This is required purely by |
| 219 |
the data that we are writing to the database, and it is only necessary |
| 220 |
if you run the application more than once without first deleting the environment. |
| 221 |
</p> |
| 222 |
<p> |
| 223 |
The implementation of <code class="function">open_db()</code> is described |
| 224 |
later in this section. |
| 225 |
</p> |
| 226 |
<pre class="programlisting"> // Open the database |
| 227 |
openDb(&dbp, progName, fileName, envp, DB_DUPSORT); </pre> |
| 228 |
<p> |
| 229 |
Now we create our threads. In this example we are using pthreads |
| 230 |
for our threading package. A description of threading (beyond how |
| 231 |
it impacts DB usage) is beyond the scope of this manual. |
| 232 |
However, the things that we are doing here should be familiar to |
| 233 |
anyone who has prior experience with any threading package. We are |
| 234 |
simply initializing a mutex, creating our threads, and then joining |
| 235 |
our threads, which causes our program to wait until the joined |
| 236 |
threads have completed before continuing operations in the main |
| 237 |
thread. |
| 238 |
</p> |
| 239 |
<pre class="programlisting"> // Initialize a pthread mutex. Used to help provide thread ids. |
| 240 |
(void)pthread_mutex_init(&thread_num_lock, NULL); |
| 241 |
|
| 242 |
// Start the writer threads. |
| 243 |
for (i = 0; i < NUMWRITERS; i++) |
| 244 |
(void)pthread_create(&writerThreads[i], NULL, |
| 245 |
writerThread, (void *)dbp); |
| 246 |
|
| 247 |
// Join the writers |
| 248 |
for (i = 0; i < NUMWRITERS; i++) |
| 249 |
(void)pthread_join(writerThreads[i], NULL); |
| 250 |
|
| 251 |
} catch(DbException &e) { |
| 252 |
std::cerr << "Error opening database environment: " |
| 253 |
<< dbHomeDir << std::endl; |
| 254 |
std::cerr << e.what() << std::endl; |
| 255 |
return (EXIT_FAILURE); |
| 256 |
} </pre> |
| 257 |
<p> |
| 258 |
Finally, to wrap up <code class="function">main()</code>, we close out our |
| 259 |
database and environment handle, as is normal for any DB |
| 260 |
application. Notice that this is where our <code class="literal">err</code> |
| 261 |
label is placed in our application. If any database operation prior |
| 262 |
to this point in the program returns an error status, the program |
| 263 |
simply jumps to this point and closes our handles if necessary |
| 264 |
before exiting the application completely. |
| 265 |
</p> |
| 266 |
<pre class="programlisting"> try { |
| 267 |
// Close our database handle if it was opened. |
| 268 |
if (dbp != NULL) |
| 269 |
dbp->close(0); |
| 270 |
|
| 271 |
// Close our environment if it was opened. |
| 272 |
if (envp != NULL) |
| 273 |
envp->close(0); |
| 274 |
} catch(DbException &e) { |
| 275 |
std::cerr << "Error closing database and environment." |
| 276 |
<< std::endl; |
| 277 |
std::cerr << e.what() << std::endl; |
| 278 |
return (EXIT_FAILURE); |
| 279 |
} |
| 280 |
|
| 281 |
// Final status message and return. |
| 282 |
|
| 283 |
std::cout << "I'm all done." << std::endl; |
| 284 |
return (EXIT_SUCCESS); |
| 285 |
} </pre> |
| 286 |
<p> |
| 287 |
Now that we have completed <code class="function">main()</code>, we need to |
| 288 |
implement the function that our writer threads will actually run. This |
| 289 |
is where the bulk of our transactional code resides. |
| 290 |
</p> |
| 291 |
<p> |
| 292 |
We start as usual with variable declarations and initialization. |
| 293 |
</p> |
| 294 |
<pre class="programlisting">// A function that performs a series of writes to a |
| 295 |
// Berkeley DB database. The information written |
| 296 |
// to the database is largely nonsensical, but the |
| 297 |
// mechanisms of transactional commit/abort and |
| 298 |
// deadlock detection are illustrated here. |
| 299 |
void * |
| 300 |
writerThread(void *args) |
| 301 |
{ |
| 302 |
int j, thread_num; |
| 303 |
int max_retries = 20; // Max retry on a deadlock |
| 304 |
char *key_strings[] = {"key 1", "key 2", "key 3", "key 4", |
| 305 |
"key 5", "key 6", "key 7", "key 8", |
| 306 |
"key 9", "key 10"}; |
| 307 |
|
| 308 |
Db *dbp = (Db *)args; |
| 309 |
DbEnv *envp = dbp->get_env(); </pre> |
| 310 |
<p> |
| 311 |
Now we want a thread number for reporting purposes. It is possible to |
| 312 |
use the <code class="literal">pthread_t</code> value directly for this purpose, |
| 313 |
but how that is done unfortunately differs depending |
| 314 |
on the pthread implementation you are using. So instead we use a |
| 315 |
mutex-protected global variable to obtain a simple integer for |
| 316 |
our reporting purposes. |
| 317 |
</p> |
| 318 |
<p> |
| 319 |
Note that we are also use this thread id for initializing a random number generator, which we do here. |
| 320 |
We use this random number generator for data generation. |
| 321 |
</p> |
| 322 |
<pre class="programlisting"> // Get the thread number |
| 323 |
(void)pthread_mutex_lock(&thread_num_lock); |
| 324 |
global_thread_num++; |
| 325 |
thread_num = global_thread_num; |
| 326 |
(void)pthread_mutex_unlock(&thread_num_lock); |
| 327 |
|
| 328 |
// Initialize the random number generator |
| 329 |
srand((u_int)pthread_self()); </pre> |
| 330 |
<p> |
| 331 |
Now we begin the loop that we use to write data to the database. |
| 332 |
|
| 333 |
<span> |
| 334 |
Notice that in this top loop, we begin a new transaction. |
| 335 |
</span> |
| 336 |
|
| 337 |
We will actually use 50 transactions per writer |
| 338 |
thread, although we will only ever have one active transaction per |
| 339 |
thread at a time. Within each transaction, we will perform 10 |
| 340 |
database writes. |
| 341 |
</p> |
| 342 |
<p> |
| 343 |
By combining multiple writes together under a single transaction, |
| 344 |
we increase the likelihood that a deadlock will occur. Normally, |
| 345 |
you want to reduce the potential for a deadlock and in this case |
| 346 |
the way to do that is to perform a single write per transaction. |
| 347 |
To avoid deadlocks, we could be using auto commit to |
| 348 |
write to our database for this workload. |
| 349 |
</p> |
| 350 |
<p> |
| 351 |
However, we want to show deadlock handling and by performing |
| 352 |
multiple writes per transaction we can actually observe deadlocks |
| 353 |
occurring. We also want to underscore the idea that you can |
| 354 |
combing multiple database operations together in a single atomic |
| 355 |
unit of work in order to improve the efficiency of your writes. |
| 356 |
</p> |
| 357 |
<pre class="programlisting"> // Perform 50 transactions |
| 358 |
for (int i=0; i<50; i++) { |
| 359 |
DbTxn *txn; |
| 360 |
bool retry = true; |
| 361 |
int retry_count = 0; |
| 362 |
// while loop is used for deadlock retries |
| 363 |
while (retry) { |
| 364 |
// try block used for deadlock detection and |
| 365 |
// general db exception handling |
| 366 |
try { |
| 367 |
|
| 368 |
// Begin our transaction. We group multiple writes in |
| 369 |
// this thread under a single transaction so as to |
| 370 |
// (1) show that you can atomically perform multiple |
| 371 |
// writes at a time, and (2) to increase the chances |
| 372 |
// of a deadlock occurring so that we can observe our |
| 373 |
// deadlock detection at work. |
| 374 |
|
| 375 |
// Normally we would want to avoid the potential for |
| 376 |
// deadlocks, so for this workload the correct thing |
| 377 |
// would be to perform our puts with auto commit. But |
| 378 |
// that would excessively simplify our example, so we |
| 379 |
// do the "wrong" thing here instead. |
| 380 |
txn = NULL; |
| 381 |
envp->txn_begin(NULL, &txn, 0); </pre> |
| 382 |
<p> |
| 383 |
Now we begin the inner loop that we use to actually |
| 384 |
perform the write. |
| 385 |
</p> |
| 386 |
<pre class="programlisting"> // Perform the database write for this transaction. |
| 387 |
for (j = 0; j < 10; j++) { |
| 388 |
Dbt key, value; |
| 389 |
key.set_data(key_strings[j]); |
| 390 |
key.set_size((strlen(key_strings[j]) + 1) * |
| 391 |
sizeof(char)); |
| 392 |
|
| 393 |
int payload = rand() + i; |
| 394 |
value.set_data(&payload); |
| 395 |
value.set_size(sizeof(int)); |
| 396 |
|
| 397 |
// Perform the database put |
| 398 |
dbp->put(txn, &key, &value, 0); |
| 399 |
} </pre> |
| 400 |
<p> |
| 401 |
Having completed the inner database write loop, we could simply |
| 402 |
commit the transaction and continue on to the next block of 10 |
| 403 |
writes. However, we want to first illustrate a few points about |
| 404 |
transactional processing so instead we call our |
| 405 |
|
| 406 |
<code class="function">countRecords()</code> |
| 407 |
|
| 408 |
function before calling the transaction |
| 409 |
commit. |
| 410 |
|
| 411 |
<code class="function">countRecords()</code> |
| 412 |
uses a cursor to read every |
| 413 |
record in the database and return a count of the number of records |
| 414 |
that it found. |
| 415 |
</p> |
| 416 |
<pre class="programlisting"> // countRecords runs a cursor over the entire database. |
| 417 |
// We do this to illustrate issues of deadlocking |
| 418 |
std::cout << thread_num << " : Found " |
| 419 |
<< countRecords(dbp, NULL) |
| 420 |
<< " records in the database." << std::endl; |
| 421 |
|
| 422 |
std::cout << thread_num << " : committing txn : " << i |
| 423 |
<< std::endl; |
| 424 |
|
| 425 |
// commit |
| 426 |
try { |
| 427 |
txn->commit(0); |
| 428 |
retry = false; |
| 429 |
txn = NULL; |
| 430 |
} catch (DbException &e) { |
| 431 |
std::cout << "Error on txn commit: " |
| 432 |
<< e.what() << std::endl; |
| 433 |
} </pre> |
| 434 |
<p> |
| 435 |
Finally, we finish our try block. Notice how we examine the |
| 436 |
exceptions to determine whether we need to |
| 437 |
abort (or abort/retry in the case of a deadlock) our current |
| 438 |
transaction. |
| 439 |
</p> |
| 440 |
<pre class="programlisting"> } catch (DbDeadlockException &de) { |
| 441 |
// First thing we MUST do is abort the transaction. |
| 442 |
if (txn != NULL) |
| 443 |
(void)txn->abort(); |
| 444 |
|
| 445 |
// Now we decide if we want to retry the operation. |
| 446 |
// If we have retried less than max_retries, |
| 447 |
// increment the retry count and goto retry. |
| 448 |
if (retry_count < max_retries) { |
| 449 |
std::cout << "############### Writer " << thread_num |
| 450 |
<< ": Got DB_LOCK_DEADLOCK.\n" |
| 451 |
<< "Retrying write operation." |
| 452 |
<< std::endl; |
| 453 |
retry_count++; |
| 454 |
retry = true; |
| 455 |
} else { |
| 456 |
// Otherwise, just give up. |
| 457 |
std::cerr << "Writer " << thread_num |
| 458 |
<< ": Got DeadLockException and out of " |
| 459 |
<< "retries. Giving up." << std::endl; |
| 460 |
retry = false; |
| 461 |
} |
| 462 |
} catch (DbException &e) { |
| 463 |
std::cerr << "db put failed" << std::endl; |
| 464 |
std::cerr << e.what() << std::endl; |
| 465 |
if (txn != NULL) |
| 466 |
txn->abort(); |
| 467 |
retry = false; |
| 468 |
} catch (std::exception &ee) { |
| 469 |
std::cerr << "Unknown exception: " << ee.what() << std::endl; |
| 470 |
return (0); |
| 471 |
} |
| 472 |
} |
| 473 |
} |
| 474 |
return (0); |
| 475 |
} </pre> |
| 476 |
<p> |
| 477 |
<span> |
| 478 |
We want to back up for a moment and take a look at the call to <code class="function">countRecords()</code>. |
| 479 |
</span> |
| 480 |
If you look at the |
| 481 |
|
| 482 |
<code class="function">countRecords()</code> |
| 483 |
function prototype at the beginning of this example, you will see that the |
| 484 |
function's second parameter takes a transaction handle. However, |
| 485 |
our usage of the function here does not pass a transaction handle |
| 486 |
through to the function. |
| 487 |
</p> |
| 488 |
<p> |
| 489 |
|
| 490 |
Because |
| 491 |
|
| 492 |
<code class="function">countRecords()</code> |
| 493 |
reads every record in the database, if used incorrectly the thread |
| 494 |
will self-deadlock. The writer thread has just written 500 records |
| 495 |
to the database, but because the transaction used for that write |
| 496 |
has not yet been committed, each of those 500 records are still |
| 497 |
locked by the thread's transaction. If we then simply run a |
| 498 |
non-transactional cursor over the database from within the same |
| 499 |
thread that has locked those 500 records, the cursor will |
| 500 |
block when it tries to read one of those transactional |
| 501 |
protected records. The thread immediately stops operation at that |
| 502 |
point while the cursor waits for the read lock it has |
| 503 |
requested. Because that read lock will never be released (the thread |
| 504 |
can never make any forward progress), this represents a |
| 505 |
self-deadlock for the the thread. |
| 506 |
</p> |
| 507 |
<p> |
| 508 |
There are three ways to prevent this self-deadlock: |
| 509 |
</p> |
| 510 |
<div class="orderedlist"> |
| 511 |
<ol type="1"> |
| 512 |
<li> |
| 513 |
<p> |
| 514 |
We can move the call to |
| 515 |
|
| 516 |
<code class="function">countRecords()</code> |
| 517 |
to a point after the thread's transaction has committed. |
| 518 |
</p> |
| 519 |
</li> |
| 520 |
<li> |
| 521 |
<p> |
| 522 |
We can allow |
| 523 |
|
| 524 |
<code class="function">countRecords()</code> |
| 525 |
to operate under the same transaction as all of the writes |
| 526 |
were performed (this is what the transaction parameter for |
| 527 |
the function is for). |
| 528 |
</p> |
| 529 |
</li> |
| 530 |
<li> |
| 531 |
<p> |
| 532 |
We can reduce our isolation guarantee for the application |
| 533 |
by allowing uncommitted reads. |
| 534 |
</p> |
| 535 |
</li> |
| 536 |
</ol> |
| 537 |
</div> |
| 538 |
<p> |
| 539 |
For this example, we choose to use option 3 (uncommitted reads) to avoid |
| 540 |
the deadlock. This means that we have to open our database such |
| 541 |
that it supports uncommitted reads, and we have to open our cursor handle |
| 542 |
so that it knows to perform uncommitted reads. |
| 543 |
</p> |
| 544 |
<p> |
| 545 |
Note that in <a class="xref" href="inmem_txnexample_c.html" title="In-Memory Transaction Example">In-Memory Transaction Example</a>, |
| 546 |
we simply perform the cursor operation using the same transaction |
| 547 |
as is used for the thread's writes. |
| 548 |
</p> |
| 549 |
<p> |
| 550 |
The following is the |
| 551 |
|
| 552 |
<code class="function">countRecords()</code> |
| 553 |
implementation. There is not anything particularly interesting |
| 554 |
about this function other than specifying uncommitted reads when |
| 555 |
we open the cursor handle, but we include the function here anyway |
| 556 |
for the sake of completeness. |
| 557 |
</p> |
| 558 |
<pre class="programlisting">// This simply counts the number of records contained in the |
| 559 |
// database and returns the result. |
| 560 |
// |
| 561 |
// Note that this method exists only for illustrative purposes. |
| 562 |
// A more straight-forward way to count the number of records in |
| 563 |
// a database is to use the Database.getStats() method. |
| 564 |
int |
| 565 |
countRecords(Db *dbp, DbTxn *txn) |
| 566 |
{ |
| 567 |
|
| 568 |
Dbc *cursorp = NULL; |
| 569 |
int count = 0; |
| 570 |
|
| 571 |
try { |
| 572 |
// Get the cursor |
| 573 |
dbp->cursor(txn, &cursorp, DB_READ_UNCOMMITTED); |
| 574 |
|
| 575 |
Dbt key, value; |
| 576 |
while (cursorp->get(&key, &value, DB_NEXT) == 0) { |
| 577 |
count++; |
| 578 |
} |
| 579 |
} catch (DbDeadlockException &de) { |
| 580 |
std::cerr << "countRecords: got deadlock" << std::endl; |
| 581 |
cursorp->close(); |
| 582 |
throw de; |
| 583 |
} catch (DbException &e) { |
| 584 |
std::cerr << "countRecords error:" << std::endl; |
| 585 |
std::cerr << e.what() << std::endl; |
| 586 |
} |
| 587 |
|
| 588 |
if (cursorp != NULL) { |
| 589 |
try { |
| 590 |
cursorp->close(); |
| 591 |
} catch (DbException &e) { |
| 592 |
std::cerr << "countRecords: cursor close failed:" << std::endl; |
| 593 |
std::cerr << e.what() << std::endl; |
| 594 |
} |
| 595 |
} |
| 596 |
|
| 597 |
return (count); |
| 598 |
} </pre> |
| 599 |
<p> |
| 600 |
Finally, we provide the implementation of our |
| 601 |
|
| 602 |
<code class="function">openDb()</code> |
| 603 |
function. This function should hold |
| 604 |
no surprises for you. Note, however, that we do specify uncommitted reads |
| 605 |
when we open the database. If we did not do this, then our |
| 606 |
|
| 607 |
<code class="function">countRecords()</code> |
| 608 |
function would cause our |
| 609 |
thread to self-deadlock because the cursor could not be opened to |
| 610 |
support uncommitted reads (that flag on the cursor open would, in fact, |
| 611 |
be silently ignored by DB). |
| 612 |
</p> |
| 613 |
<pre class="programlisting">// Open a Berkeley DB database |
| 614 |
int |
| 615 |
openDb(Db **dbpp, const char *progname, const char *fileName, |
| 616 |
DbEnv *envp, u_int32_t extraFlags) |
| 617 |
{ |
| 618 |
int ret; |
| 619 |
u_int32_t openFlags; |
| 620 |
|
| 621 |
try { |
| 622 |
Db *dbp = new Db(envp, 0); |
| 623 |
|
| 624 |
// Point to the new'd Db |
| 625 |
*dbpp = dbp; |
| 626 |
|
| 627 |
if (extraFlags != 0) |
| 628 |
ret = dbp->set_flags(extraFlags); |
| 629 |
|
| 630 |
// Now open the database |
| 631 |
openFlags = DB_CREATE | // Allow database creation |
| 632 |
DB_READ_UNCOMMITTED | // Allow uncommitted reads |
| 633 |
DB_AUTO_COMMIT | /* Allow auto commit */ |
| 634 |
DB_THREAD; /* Cause the database to |
| 635 |
be free-threaded */ |
| 636 |
|
| 637 |
dbp->open(NULL, // Txn pointer |
| 638 |
fileName, // File name |
| 639 |
NULL, // Logical db name |
| 640 |
DB_BTREE, // Database type (using btree) |
| 641 |
openFlags, // Open flags |
| 642 |
0); // File mode. Using defaults |
| 643 |
} catch (DbException &e) { |
| 644 |
std::cerr << progname << "open_db: db open failed:" << std::endl; |
| 645 |
std::cerr << e.what() << std::endl; |
| 646 |
return (EXIT_FAILURE); |
| 647 |
} |
| 648 |
|
| 649 |
return (EXIT_SUCCESS); |
| 650 |
} </pre> |
| 651 |
<p> |
| 652 |
This completes our transactional example. If you would like to |
| 653 |
experiment with this code, you can find the example in the following |
| 654 |
location in your DB distribution: |
| 655 |
</p> |
| 656 |
<pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_cxx/txn_guide</pre> |
| 657 |
</div> |
| 658 |
<div class="navfooter"> |
| 659 |
<hr /> |
| 660 |
<table width="100%" summary="Navigation footer"> |
| 661 |
<tr> |
| 662 |
<td width="40%" align="left"><a accesskey="p" href="wrapup.html">Prev</a> </td> |
| 663 |
<td width="20%" align="center"> |
| 664 |
<a accesskey="u" href="wrapup.html">Up</a> |
| 665 |
</td> |
| 666 |
<td width="40%" align="right"> <a accesskey="n" href="inmem_txnexample_c.html">Next</a></td> |
| 667 |
</tr> |
| 668 |
<tr> |
| 669 |
<td width="40%" align="left" valign="top">Chapter 6. Summary and Examples </td> |
| 670 |
<td width="20%" align="center"> |
| 671 |
<a accesskey="h" href="index.html">Home</a> |
| 672 |
</td> |
| 673 |
<td width="40%" align="right" valign="top"> In-Memory Transaction Example</td> |
| 674 |
</tr> |
| 675 |
</table> |
| 676 |
</div> |
| 677 |
</body> |
| 678 |
</html> |