Debian Codegraph @

listings/chapter-4/critical-section.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <pthread.h>
8 #include <stdio.h>
9 #include <string.h>
10
11 /* An array of balances in accounts, indexed by account number. */
12
13 float* account_balances;
14
15 /* Transfer DOLLARS from account FROM_ACCT to account TO_ACCT. Return
16 0 if the transaction succeeded, or 1 if the balance FROM_ACCT is
17 too small. */
18
19 int process_transaction (int from_acct, int to_acct, float dollars)
20 {
21 int old_cancel_state;
22
23 /* Check the balance in FROM_ACCT. */
24 if (account_balances[from_acct] < dollars)
25 return 1;
26
27 /* Begin critical section. */
28 pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &old_cancel_state);
29 /* Move the money. */
30 account_balances[to_acct] += dollars;
31 account_balances[from_acct] -= dollars;
32 /* End critical section. */
33 pthread_setcancelstate (old_cancel_state, NULL);
34
35 return 0;
36 }