ch4-critical-section
Chapter_4 detach | tsd |
critical-section.c ALP, p. 71
#include <stdio.h> // for printf(), scanf(), fprintf(), stderr, NULL
#include <pthread.h> // for pthread_t, pthread_setcancelstate(),
// PTHREAD_CANCEL_DISABLE
#define MAXACCTS 100 // max no of accounts
/* An array of balances in accounts, indexed by account number */
float account_balances[MAXACCTS];
// return 0 for success, 1 if there is not enough money
int process_transaction (int from_acct, int to_acct, float dollars);
int main() // single-threaded program
{
int acc1 = 0, acc2 = 1, ret; // return value
account_balances[acc1] = 1000;
account_balances[acc2] = 0;
printf("Account 1: %.2f\n", account_balances[acc1]);
printf("Account 2: %.2f\n", account_balances[acc2]);
float sum;
printf("Transfer money: ");
scanf("%f", &sum);
if (sum < 0)
{
fprintf(stderr, "Sum must be positive\n");
return 1; // end program, signalling error
}
// else
ret = process_transaction(acc1, acc2, sum);
if (ret == 1)
{printf("Not enough money: %.2f < %.2f\n",
account_balances[acc1], sum);}
else // ret == 0
{
printf("Account 1: %.2f\n", account_balances[acc1]);
printf("Account 2: %.2f\n", account_balances[acc2]);
}
return 0;
}
/* Transfer `dollars' from one account to the other.
Return 0 for success, 1 if not enough money. */
int process_transaction (int from_acct, int to_acct, float dollars)
{
int old_cancel_state; // it will be set in pthread_setcancelstate()
/* Check the balance in FROM_ACCT. */
if (account_balances[from_acct] < dollars)
{return 1;} // not enough money
// else
/* Begin critical section: */
pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &old_cancel_state);
/* Move the money: */
account_balances[to_acct] += dollars;
account_balances[from_acct] -= dollars;
/* End critical section. */
pthread_setcancelstate (old_cancel_state, NULL);
return 0;
}
/*
gcc critical-section.c -o critical-section -lpthread
./critical-section
Account 1: 1000.00
Account 2: 0.00
Transfer money: -100
Sum must be positive
./critical-section
Account 1: 1000.00
Account 2: 0.00
Transfer money: 0
Account 1: 1000.00
Account 2: 0.00
./critical-section
Account 1: 1000.00
Account 2: 0.00
Transfer money: 1500
Not enough money: 1000.00 < 1500.00
./critical-section
Account 1: 1000.00
Account 2: 0.00
Transfer money: 500
Account 1: 500.00
Account 2: 500.00
*/
Chapter_4 detach | BACK_TO_TOP | tsd |
Comments
Post a Comment