1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
int balance = 100;
pthread_t wThread1;
pthread_t wThread2;
pthread_t dThread1;
pthread_t dThread2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *p1;
void *p2;
void *p3;
void *p4;
void withdraw(int tid){
pthread_mutex_lock(&mutex);
for (int i=0; i<10; i++){
int readbalance = balance;
printf("At time %d, the balance for withdrawal thread %d is %d", i, tid, balance);
if (readbalance < 10)
printf("not enough");
else {
readbalance -= 10;
usleep(1);
balance = readbalance;
printf("At time %d, the balance after withdrawal thread %d is %d", i, tid, balance);
usleep(1);
}
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void deposit(int tid){
pthread_mutex_lock(&mutex);
for (int i=0; i<10; i++){
int readbalance = balance;
printf("At time %d, the balance before depositing thread %d is %d", i, tid, balance);
readbalance += 11;
usleep(10);
balance = readbalance;
printf("At time %d, the balance after depositing thread %d is %d", i, tid, balance);
usleep(10);
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(){
pthread_create(&wThread1, NULL, (void *)withdraw, &p1);
pthread_create(&wThread2, NULL, (void *)withdraw, &p2);
pthread_create(&dThread1, NULL, (void *)deposit, &p3);
pthread_create(&dThread2, NULL, (void *)deposit, &p4);
pthread_join(wThread1, NULL);
pthread_join(wThread2, NULL);
pthread_join(dThread1, NULL);
pthread_join(dThread2, NULL);
return 0;
}
|