Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*=========================================================*/
- 2 /* race.c --- for playing with ECE437 */
- 3 /*=========================================================*/
- 4 #include <unistd.h>
- 5 #include <stdio.h>
- 6 #include <stdlib.h>
- 7 #include <pthread.h>
- 8 struct {int balance[2];} Bank={{100,100}}; //global variable defined
- 9 //Sem437* lock = (Sem437*)malloc(sizeof(Sem437));
- 10 typedef struct {int S;} Sem437;
- 11
- 12 void Sem437Init(Sem437* sem, int a)
- 13 {
- 14 printf("in init function\n");
- 15 sem->S = 1;
- 16 printf("leaving init function\n");
- 17 }
- 18
- 19 void Sem437P(Sem437* sem)
- 20 {
- 21 while(&sem->S == 0)
- 22 ;
- 23 sem->S--;
- 24 }
- 25
- 26 void Sem437V(Sem437* sem)
- 27 {
- 28 sem->S++;
- 29 }
- 30 // Sem437* lock;
- 31 // Sem437Init(lock, 1);
- 32 Sem437* lock = (Sem437*)malloc(sizeof(Sem437));
- 33 //int a = 1;
- 34 //lock->S = 1;
- 35
- 36 void* MakeTransactions() { //routine for thread execution
- 37 int i, j, tmp1, tmp2, rint; double dummy;
- 38
- 39 Sem437P(lock);
- 40 for (i=0; i < 100; i++) { rint = (rand()%30)-15;
- 41 if (((tmp1=Bank.balance[0])+rint)>=0 && ((tmp2=Bank.balance[1])-rint)>=0) {
- 42 // Sem437P(lock);
- 43 Bank.balance[0] = tmp1 + rint;
- 44 // Sem437V(lock);
- 45 for (j=0; j < rint*100; j++) {dummy=2.345*8.765/1.234;}
- 46 // Sem437P(lock);
- 47 Bank.balance[1] = tmp2 - rint;
- 48 // Sem437V(lock);
- 49 }
- 50 }
- 51 Sem437V(lock);
- 52 return NULL;
- 53 }
- 54
- 55 int main(int argc, char **argv) {
- 56 int i; void* voidptr=NULL; pthread_t tid[2];
- 57 //Sem437* lock;
- 58 //Sem437* lock = (Sem437*)malloc(sizeof(Sem437));
- 59 int a = 1;
- 60 lock->S = 1;
- 61 printf("got to here\n");
- 62 //Sem437Init(lock, a);
- 63 printf("Lock has value %d \n", lock->S);
- 64
- 65 srand(getpid());
- 66 printf("Init balances A:%d + B:%d ==> %d!\n",
- 67 Bank.balance[0],Bank.balance[1],Bank.balance[0]+Bank.balance[1]);
- 68 for (i=0; i<2; i++) if (pthread_create(&tid[i],NULL,MakeTransactions, NULL)) {
- 69 fprintf(stderr, "Error in thread creating\n"); return(1); }
- 70 for (i=0; i<2; i++) if (pthread_join(tid[i], (void*)&voidptr)) {
- 71 fprintf(stderr, "Error in thread joining\n"); return(1);}
- 72 printf("Let's check the balances A:%d + B:%d ==> %d ?= 200\n",
- 73 Bank.balance[0],Bank.balance[1],Bank.balance[0]+Bank.balance[1]);
- 74 return 0;
- 75 }
- 76
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement