Debian Codegraph @

docs/gsg_txn/C/lockingsubsystem.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>The Locking Subsystem</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="txnconcurrency.html" title="Chapter 4. Concurrency" />
11 <link rel="prev" href="blocking_deadlocks.html" title="Locks, Blocks, and Deadlocks" />
12 <link rel="next" href="isolation.html" title="Isolation" />
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">The Locking Subsystem</th>
22 </tr>
23 <tr>
24 <td width="20%" align="left"><a accesskey="p" href="blocking_deadlocks.html">Prev</a> </td>
25 <th width="60%" align="center">Chapter 4. Concurrency</th>
26 <td width="20%" align="right"> <a accesskey="n" href="isolation.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="lockingsubsystem"></a>The Locking Subsystem</h2>
36 </div>
37 </div>
38 </div>
39 <div class="toc">
40 <dl>
41 <dt>
42 <span class="sect2">
43 <a href="lockingsubsystem.html#configuringlock">Configuring the Locking Subsystem</a>
44 </span>
45 </dt>
46 <dt>
47 <span class="sect2">
48 <a href="lockingsubsystem.html#configdeadlkdetect">Configuring Deadlock Detection</a>
49 </span>
50 </dt>
51 <dt>
52 <span class="sect2">
53 <a href="lockingsubsystem.html#deadlockresolve">Resolving Deadlocks</a>
54 </span>
55 </dt>
56 <dt>
57 <span class="sect2">
58 <a href="lockingsubsystem.html#setpriority">Setting Transaction Priorities</a>
59 </span>
60 </dt>
61 </dl>
62 </div>
63 <p>
64 In order to allow concurrent operations, DB provides the locking
65 subsystem. This subsystem provides inter- and intra- process
66 concurrency mechanisms. It is extensively used by DB concurrent
67 applications, but it can also be generally used for non-DB
68 resources.
69 </p>
70 <p>
71 This section describes the locking subsystem as it is used to
72 protect DB resources. In particular, issues on configuration are
73 examined here. For information on using the locking subsystem to
74 manage non-DB resources, see the
75 <em class="citetitle">Berkeley DB Programmer's Reference Guide</em>.
76 </p>
77 <div class="sect2" lang="en" xml:lang="en">
78 <div class="titlepage">
79 <div>
80 <div>
81 <h3 class="title"><a id="configuringlock"></a>Configuring the Locking Subsystem</h3>
82 </div>
83 </div>
84 </div>
85 <p>
86 You initialize the locking subsystem by specifying
87 <span>
88 <code class="literal">DB_INIT_LOCK</code> to the
89 <code class="methodname">DB_ENV-&gt;open()</code>
90
91 method.
92 </span>
93
94 </p>
95 <p>
96 Before opening your environment, you can configure various
97 values for your locking subsystem. Note that these
98 limits can only be configured before the environment is
99 opened. Also, these methods configure the entire environment,
100 not just a specific environment handle.
101 </p>
102 <p>
103 Finally, each bullet below identifies the
104 <code class="filename">DB_CONFIG</code> file parameter that can be used
105 to specify the specific locking limit. If used, these
106 <code class="filename">DB_CONFIG</code> file parameters override any
107 value that you might specify using the environment handle.
108 </p>
109 <p>
110 The limits that you can configure are as follows:
111 </p>
112 <div class="itemizedlist">
113 <ul type="disc">
114 <li>
115 <p>
116 The number of lockers supported by the environment.
117 This value is used by the environment when it is
118 opened to estimate the amount of space that it
119 should allocate for various internal data
120 structures. By default, 1,000 lockers are
121 supported.
122 </p>
123 <p>
124 To configure this value, use the
125
126 <span>
127 <code class="methodname">DB_ENV-&gt;set_memory_init()</code>
128
129 method to configure the <code class="literal">DB_MEM_LOCKER</code> structure.
130 </span>
131
132 </p>
133 <p>
134 As an alternative to this method, you can configure this
135 value using the <code class="filename">DB_CONFIG</code> file's
136 <code class="literal">set_lk_max_lockers</code> parameter.
137 </p>
138 </li>
139 <li>
140 <p>
141 The number of locks supported by the environment.
142 By default, 1,000 locks are supported.
143 </p>
144 <p>
145 To configure this value, use the
146 <span>
147 <code class="methodname">DB_ENV-&gt;set_memory_init()</code>
148
149 method to configure the <code class="literal">DB_MEM_LOCK</code> structure.
150 </span>
151
152 </p>
153 <p>
154 As an alternative to this method, you can configure this
155 value using the <code class="filename">DB_CONFIG</code> file's
156 <code class="literal">set_lk_max_locks</code> parameter.
157 </p>
158 </li>
159 <li>
160 <p>
161 The number of locked objects supported by the
162 environment. By default, 1,000 objects can be
163 locked.
164 </p>
165 <p>
166 To configure this value, use the
167 <span>
168 <code class="methodname">DB_ENV-&gt;set_memory_init()</code>
169
170 method to configure the <code class="literal">DB_MEM_LOCKOBJECT</code> structure.
171 </span>
172
173 </p>
174 <p>
175 As an alternative to this method, you can configure this
176 value using the <code class="filename">DB_CONFIG</code> file's
177 <code class="literal">set_lk_max_objects</code> parameter.
178 </p>
179 </li>
180 </ul>
181 </div>
182 <p>
183 For a definition of lockers, locks, and locked objects, see
184 <a class="xref" href="blocking_deadlocks.html#lockresources" title="Lock Resources">Lock Resources</a>.
185 </p>
186 <p>
187 For example, to configure the number of locks that your
188 environment can use:
189 </p>
190 <pre class="programlisting">#include &lt;stdio.h&gt;
191 #include &lt;stdlib.h&gt;
192
193 #include "db.h"
194
195 int
196 main(void)
197 {
198 int ret, ret_c;
199 u_int32_t env_flags;
200 DB_ENV *envp;
201 const char *db_home_dir = "/tmp/myEnvironment";
202
203 envp = NULL;
204
205 /* Open the environment */
206 ret = db_env_create(&amp;envp, 0);
207 if (ret != 0) {
208 fprintf(stderr, "Error creating environment handle: %s\n",
209 db_strerror(ret));
210 return (EXIT_FAILURE);
211 }
212
213 env_flags = DB_CREATE | /* If the environment does not
214 * exist, create it. */
215 DB_INIT_LOCK | /* Initialize locking */
216 DB_INIT_LOG | /* Initialize logging */
217 DB_INIT_MPOOL | /* Initialize the cache */
218 DB_THREAD | /* Free-thread the env handle. */
219 DB_INIT_TXN; /* Initialize transactions */
220
221 /* Configure max locks */
222 ret = envp-&gt;set_memory_init(envp, DB_MEM_LOCK, 5000);
223 if (ret != 0) {
224 fprintf(stderr, "Error configuring locks: %s\n",
225 db_strerror(ret));
226 goto err;
227 }
228
229 /* Open the environment. */
230 ret = envp-&gt;open(envp, db_home_dir, env_flags, 0);
231 if (ret != 0) {
232 fprintf(stderr, "Error opening environment: %s\n",
233 db_strerror(ret));
234 goto err;
235 }
236
237 err:
238 /* Close the environment */
239 if (envp != NULL) {
240 ret_c = envp-&gt;close(envp, 0);
241 if (ret_c != 0) {
242 fprintf(stderr, "environment close failed: %s\n",
243 db_strerror(ret_c));
244 ret = ret_c;
245 }
246 }
247
248 return (ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
249 } </pre>
250 </div>
251 <div class="sect2" lang="en" xml:lang="en">
252 <div class="titlepage">
253 <div>
254 <div>
255 <h3 class="title"><a id="configdeadlkdetect"></a>Configuring Deadlock Detection</h3>
256 </div>
257 </div>
258 </div>
259 <p>
260 In order for DB to know that a deadlock has occurred,
261 some mechanism must be used to perform deadlock
262 detection. There are three ways that deadlock detection can
263 occur:
264 </p>
265 <div class="orderedlist">
266 <ol type="1">
267 <li>
268 <p>
269 Allow DB to internally detect deadlocks as they
270 occur.
271 </p>
272 <p>
273 To do this, you use
274 <span><code class="methodname">DB_ENV-&gt;set_lk_detect()</code>.</span>
275
276
277 This method causes DB to walk its internal lock table
278 looking for a deadlock whenever a lock request
279 is blocked. This method also identifies how DB decides which lock
280 requests are rejected when deadlocks are detected. For example,
281 DB can decide to reject the lock request for the transaction
282 that has the most number of locks, the least number of locks,
283 holds the oldest lock, holds the most number of write locks, and
284 so forth (see the API reference documentation for a complete
285 list of the lock detection policies).
286 </p>
287 <p>
288 You can call this method at any time during your application's
289 lifetime, but typically it is used before you open your environment.
290 </p>
291 <p>
292 Note that how you want DB to decide which thread of control should break a deadlock is
293 extremely dependent on the nature of your application. It is not unusual for some performance
294 testing to be required in order to make this determination. That said, a transaction that is
295 holding the most number of locks is usually indicative of the transaction that has performed
296 the most amount of work. Frequently you will not want a transaction that has performed a lot of
297 work to abandon its efforts and start all over again. It is not therefore uncommon for
298 application developers to initially select the transaction with the <span class="emphasis"><em>minimum</em></span>
299 number of write locks to break the deadlock.
300 </p>
301 <p>
302 Using this mechanism for deadlock detection means
303 that your application will never have to wait on a
304 lock before discovering that a deadlock has
305 occurred. However, walking the lock table every
306 time a lock request is blocked can be expensive
307 from a performance perspective.
308 </p>
309 </li>
310 <li>
311 <p>
312 Use a dedicated thread or external process to perform
313 deadlock detection. Note that this thread must be
314 performing no other database operations beyond deadlock
315 detection.
316 </p>
317 <p>
318 To externally perform lock detection, you can use
319 either the
320 <code class="methodname">DB_ENV-&gt;lock_detect()</code>
321
322
323 method, or use the
324 <span class="command"><strong>db_deadlock</strong></span> command line
325 utility. This method (or command) causes DB to walk the
326 lock table looking for deadlocks.
327 </p>
328 <p>
329 Note that like
330 <span><code class="methodname">DB_ENV-&gt;set_lk_detect()</code>,</span>
331
332
333 you also use this method (or command line utility)
334 to identify which lock requests are rejected in the
335 event that a deadlock is detected.
336 </p>
337 <p>
338 Applications that perform deadlock detection in
339 this way typically run deadlock detection between every few
340 seconds and a minute. This means that your
341 application may have to wait to be notified of a
342 deadlock, but you also save the overhead of walking
343 the lock table every time a lock request is blocked.
344 </p>
345 </li>
346 <li>
347 <p>
348 Lock timeouts.
349 </p>
350 <p>
351 You can configure your locking subsystem such that
352 it times out any lock that is not released within a
353 specified amount of time. To do this, use the
354 <span><code class="methodname">DB_ENV-&gt;set_timeout()</code></span>
355
356
357 method.
358 Note that lock timeouts are only checked when a
359 lock request is blocked or when deadlock
360 detection is otherwise performed. Therefore, a lock can have timed out and still be held for
361 some length of time until DB has a reason to examine its locking tables.
362 </p>
363 <p>
364 Be aware that extremely long-lived transactions, or
365 operations that hold locks for a long time, may be
366 inappropriately timed out before the transaction or
367 operation has a chance to complete. You should
368 therefore use this mechanism only if you know your
369 application will hold locks for very short periods
370 of time.
371 </p>
372 </li>
373 </ol>
374 </div>
375 <p>
376 For example, to configure your application such that DB
377 checks the lock table for deadlocks every time a lock
378 request is blocked:
379 </p>
380 <pre class="programlisting">#include &lt;stdio.h&gt;
381 #include &lt;stdlib.h&gt;
382
383 #include "db.h"
384
385 int
386 main(void)
387 {
388 int ret, ret_c;
389 u_int32_t db_flags, env_flags;
390 DB *dbp;
391 DB_ENV *envp;
392 DB_TXN *txn;
393 const char *db_home_dir = "/tmp/myEnvironment";
394 const char *file_name = "mydb.db";
395
396 envp = NULL;
397
398 /* Open the environment */
399 ret = db_env_create(&amp;envp, 0);
400 if (ret != 0) {
401 fprintf(stderr, "Error creating environment handle: %s\n",
402 db_strerror(ret));
403 return (EXIT_FAILURE);
404 }
405
406 env_flags = DB_CREATE | /* If the environment does not
407 * exist, create it. */
408 DB_INIT_LOCK | /* Initialize locking */
409 DB_INIT_LOG | /* Initialize logging */
410 DB_INIT_MPOOL | /* Initialize the cache */
411 DB_THREAD | /* Free-thread the env handle. */
412 DB_INIT_TXN; /* Initialize transactions */
413
414 /*
415 * Configure db to perform deadlock detection internally, and to
416 * choose the transaction that has performed the least amount of
417 * writing to break the deadlock in the event that one is detected.
418 */
419 ret = envp-&gt;set_lk_detect(envp, DB_LOCK_MINWRITE);
420 if (ret != 0) {
421 fprintf(stderr, "Error setting lk detect: %s\n",
422 db_strerror(ret));
423 goto err;
424 }
425
426 ret = envp-&gt;open(envp, db_home_dir, env_flags, 0);
427 if (ret != 0) {
428 fprintf(stderr, "Error opening environment: %s\n",
429 db_strerror(ret));
430 goto err;
431 }
432
433 /*
434 * From here, you open your databases, proceed with your
435 * database operations, and respond to deadlocks as
436 * is normal (omitted for brevity).
437 */
438
439 ... </pre>
440 <p>
441 Finally, the following command line call causes
442 deadlock detection to be run against the
443 environment contained in <code class="literal">/export/dbenv</code>. The
444 transaction with the youngest lock is chosen to break the
445 deadlock:
446 </p>
447 <pre class="programlisting">&gt; /usr/local/db_install/bin/db_deadlock -h /export/dbenv -a y</pre>
448 <p>
449 For more information, see the
450 <a class="ulink" href="http://download.oracle.com/docs/cd/E17076_02/html/api_reference/C/db_deadlock.html" target="_top">
451 <code class="literal">db_deadlock</code> reference documentation.
452 </a>
453 </p>
454 </div>
455 <div class="sect2" lang="en" xml:lang="en">
456 <div class="titlepage">
457 <div>
458 <div>
459 <h3 class="title"><a id="deadlockresolve"></a>Resolving Deadlocks</h3>
460 </div>
461 </div>
462 </div>
463 <p>
464 When DB determines that a deadlock has occurred, it will
465 select a thread of control to resolve the deadlock and then
466 <span>
467 return <code class="literal">DB_LOCK_DEADLOCK</code> to that
468 thread.
469 </span>
470
471
472
473 If a deadlock is detected, the thread must:
474 </p>
475 <div class="orderedlist">
476 <ol type="1">
477 <li>
478 <p>
479 Cease all read and write operations.
480 </p>
481 </li>
482 <li>
483 <p>
484 Close all open cursors.
485 </p>
486 </li>
487 <li>
488 <p>
489 Abort the transaction.
490 </p>
491 </li>
492 <li>
493 <p>
494 Optionally retry the operation. If your application
495 retries deadlocked operations, the new attempt must
496 be made using a new transaction.
497 </p>
498 </li>
499 </ol>
500 </div>
501 <div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
502 <h3 class="title">Note</h3>
503 <p>
504 If a thread has deadlocked, it may not make any
505 additional database calls using the handle that has
506 deadlocked.
507 </p>
508 </div>
509 <p>
510 For example:
511 </p>
512 <pre class="programlisting">retry:
513 ret = envp-&gt;txn_begin(envp, NULL, &amp;txn, 0);
514 if (ret != 0) {
515 envp-&gt;err(envp, ret, "txn_begin failed");
516 return (EXIT_FAILURE);
517 }
518 ...
519 /* key and data are Dbts. Their usage is omitted for brevity. */
520 ...
521 switch (ret = dbp-&gt;put(dbp, txn, &amp;key, &amp;data, 0)) {
522 case 0:
523 break;
524 /* Deadlock handling goes here */
525 case DB_LOCK_DEADLOCK:
526 /* Abort the transaction */
527 (void)txn-&gt;abort(txn);
528
529 /*
530 * retry_count is a counter used to identify how many times
531 * we've retried this operation. To avoid the potential for
532 * endless looping, we won't retry more than
533 * MAX_DEADLOCK_RETRIES times.
534 */
535 if (retry_count &lt; MAX_DEADLOCK_RETRIES) {
536 printf("Got DB_LOCK_DEADLOCK.\n");
537 printf("Retrying write operation.\n");
538 retry_count++;
539 goto retry;
540 }
541 printf("Got DB_LOCK_DEADLOCK and out of retries.");
542 printf("Giving up.\n");
543 return (EXIT_FAILURE);
544 default:
545 /* If some random database error occurs, we just give up */
546 envp-&gt;err(envp, ret, "db put failed");
547 ret = txn-&gt;abort(txn);
548 if (ret != 0) {
549 envp-&gt;err(envp, ret, "txn abort failed");
550 return (EXIT_FAILURE);
551 }
552 }
553 /* If all goes well, commit the transaction */
554 ret = txn-&gt;commit(txn, 0);
555 if (ret != 0) {
556 envp-&gt;err(envp, ret, "txn commit failed");
557 return (EXIT_FAILURE);
558 }
559
560 return (EXIT_SUCCESS); </pre>
561 </div>
562 <div class="sect2" lang="en" xml:lang="en">
563 <div class="titlepage">
564 <div>
565 <div>
566 <h3 class="title"><a id="setpriority"></a>Setting Transaction Priorities</h3>
567 </div>
568 </div>
569 </div>
570 <p>
571 Normally when a thread of control must be selected to
572 resolve a deadlock, DB decides which thread will
573 perform the resolution; you have no way of knowing in
574 advance which thread will be selected to resolve the
575 deadlock.
576 </p>
577 <p>
578 However, there may be situations where you know it is
579 better for one thread to resolve a deadlock over another
580 thread. As an example, if you have a background thread
581 running data management activities, and another thread
582 responding to user requests, you might want deadlock
583 resolution to occur in the background thread because you
584 can better afford the throughput costs there. Under these
585 circumstances, you can identify which thread of control
586 will be selected for resolved deadlocks by setting a
587 transaction priorities.
588 </p>
589 <p>
590 When two transactions are deadlocked, DB will abort the
591 transaction with the lowest priority. By default, every
592 transaction is given a priority of 100. However, you can
593 set a different priority on a transaction-by-transaction
594 basis by using the
595 <code class="methodname">DB_TXN-&gt;set_priority()</code>
596
597
598 method.
599 </p>
600 <p>
601 When two or more transactions are tied for the lowest
602 priority, the tie is broken based on the policy provided to
603 <span>
604 the
605 <code class="methodname">DB_ENV-&gt;lock_detect()</code>
606
607 method's <code class="literal">atype</code> parameter.
608 </span>
609
610 </p>
611 <p>
612 A transaction's priority can be changed at any time after
613 the transaction handle has been created and before the
614 transaction has been resolved (committed or aborted).
615 For example:
616 </p>
617 <pre class="programlisting">#include &lt;stdio.h&gt;
618 #include &lt;stdlib.h&gt;
619
620 #include "db.h"
621
622 int
623 main(void)
624 {
625 int ret, ret_c;
626 u_int32_t db_flags, env_flags;
627 DB *dbp;
628 DB_ENV *envp;
629 DBT key, data;
630 DB_TXN *txn;
631
632 ...
633 // Open the environment and database as normal.
634 // Omitted for brevity
635 ...
636
637 /* Get the txn handle */
638 txn = NULL;
639 ret = envp-&gt;txn_begin(envp, NULL, &amp;txn, 0);
640 if (ret != 0) {
641 envp-&gt;err(envp, ret, "Transaction begin failed.");
642 goto err;
643 }
644
645 <strong class="userinput"><code>ret = txn-&gt;set_priority(txn, 200);
646 if (ret != 0) {
647 envp-&gt;err(envp, ret, "Transaction set_priority failed.");
648 goto err;
649 }</code></strong>
650
651 /*
652 * Perform the database write. If this fails, abort the transaction.
653 */
654 ret = dbp-&gt;put(dbp, txn, &amp;key, &amp;data, 0);
655 if (ret != 0) {
656 envp-&gt;err(envp, ret, "Database put failed.");
657 txn-&gt;abort(txn);
658 goto err;
659 }
660
661 /*
662 * Commit the transaction.
663 */
664 ret = txn-&gt;commit(txn, 0);
665 if (ret != 0) {
666 envp-&gt;err(envp, ret, "Transaction commit failed.");
667 goto err;
668 }
669
670 err:
671 ...
672 // Close the database and environment here, and exit the application.
673 // Omitted for brevity.
674 } </pre>
675 </div>
676 </div>
677 <div class="navfooter">
678 <hr />
679 <table width="100%" summary="Navigation footer">
680 <tr>
681 <td width="40%" align="left"><a accesskey="p" href="blocking_deadlocks.html">Prev</a> </td>
682 <td width="20%" align="center">
683 <a accesskey="u" href="txnconcurrency.html">Up</a>
684 </td>
685 <td width="40%" align="right"> <a accesskey="n" href="isolation.html">Next</a></td>
686 </tr>
687 <tr>
688 <td width="40%" align="left" valign="top">Locks, Blocks, and Deadlocks </td>
689 <td width="20%" align="center">
690 <a accesskey="h" href="index.html">Home</a>
691 </td>
692 <td width="40%" align="right" valign="top"> Isolation</td>
693 </tr>
694 </table>
695 </div>
696 </body>
697 </html>