Advertisement
Guest User

Untitled

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