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 74 75 76 77 78 79 80 81 82 83 84 85 86
| #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h>
#define THREAD_NUM 20
pthread_mutex_t AccountA_mutex; pthread_mutex_t AccountB_mutex; struct Account { char account_name[1]; int balance; }; struct Account accountA = {'A', 100000}; struct Account accountB = {'B', 200000}; void * accountAB (void* amount_ptr) { int amount = *((int*)amount_ptr); pthread_mutex_lock(&AccountA_mutex); if (accountA.balance < amount) { printf("There is not enough memory in Account A!\n"); pthread_mutex_unlock(&AccountA_mutex); pthread_exit((void *)1); } accountA.balance -=amount; sleep(2); pthread_mutex_lock(&AccountB_mutex); accountB.balance +=amount; pthread_mutex_unlock(&AccountA_mutex); pthread_mutex_unlock(&AccountB_mutex); }
void * accountBA (void* amount_ptr) { int amount = *((int*)amount_ptr); pthread_mutex_lock(&AccountB_mutex); if (accountB.balance < amount) { printf("There is not enough memory in Account B!\n"); pthread_mutex_unlock(&AccountB_mutex); pthread_exit((void *)1); } accountB.balance -=amount; pthread_mutex_lock(&AccountA_mutex); accountA.balance +=amount; pthread_mutex_unlock(&AccountB_mutex); pthread_mutex_unlock(&AccountA_mutex); }
int main(int argc, char* argv[]) { int threadid[THREAD_NUM]; pthread_t pthread[THREAD_NUM]; void* thResState; int res, flag; int transfer_amount[THREAD_NUM] = {100, 200, 300, 400,100,200,300,400,500,600,700,800,900,800,700,600,500,400,300,200};
pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
for(flag=0; flag<THREAD_NUM; flag++){ if(flag%2 == 0){ if (threadid[flag] = pthread_create(&pthread[flag], &attr , accountAB, \ (void*)&transfer_amount[flag]) < 0){ printf("Thread %d creation failed\n", flag); exit (1); } } else{ if (threadid[flag] = pthread_create(&pthread[flag], &attr , accountBA, \ (void*)&transfer_amount[flag]) < 0) { printf("Thread %d creation failed\n", flag); exit (1); } } }
for(flag=0; flag<THREAD_NUM; flag++){ res = pthread_join(pthread[flag], &thResState); if (res != 0){ perror("Thread join failed"); exit(-1); } printf("thread success id %u state code %d\n",threadid[flag],thResState); }
printf("Transitions are in progress.."); printf("\nAll the money is transferred !!\n"); }
|