[关闭]
@rg070836rg 2015-11-13T10:22:35.000000Z 字数 1290 阅读 1217

在此处输入标题

未分类


  1. #include"stdlib.h"
  2. #include"stdio.h"
  3. #include"time.h"
  4. #include"sched.h"
  5. #include"linux/sem.h"
  6. #include"errno.h"
  7. #define NCNT 10
  8. #define INIT_BANK 10000
  9. #define STACK_FRAME 8192
  10. void* ThreadProc(int* arg);
  11. long account[NCNT];
  12. unsigned long ntrans;
  13. int main()
  14. {
  15. int nRetCode = 0;
  16. int i;
  17. int clone_flag;
  18. int arg[NCNT];
  19. char *stack[NCNT], *st[NCNT];
  20. char ch;
  21. ntrans = 0;
  22. clone_flag = CLONE_VM|CLONE_SIGHAND|CLONE_FS|CLONE_FILES;
  23. for(i=0; i<NCNT; i++)
  24. {
  25. arg[i] = i;
  26. account[i] = INIT_BANK;
  27. }
  28. for(i=0; i<NCNT; i++)
  29. {
  30. st[i] = (char*)malloc(STACK_FRAME);
  31. stack[i] = st[i]+STACK_FRAME;
  32. clone((void*)ThreadProc, stack[i], clone_flag, &arg[i]);
  33. }
  34. for(i=0; i<NCNT; i++)
  35. free(st[i]);
  36. while((ch = getchar())! = 'c')
  37. return nRetCode;
  38. }
  39. void test()
  40. {
  41. int i;
  42. long sum = 0;
  43. for(i=0; i<NCNT; i++) sum += account[i];
  44. printf("trans=%ld sum=%ld\n", ntrans, sum);
  45. for(i=0; i<NCNT; i++)
  46. printf("[%2d]=%5ld/n", i, account[i]);
  47. printf("\n");
  48. }
  49. void transfer(int from, int to, int amount)
  50. {
  51. int t;
  52. int i;
  53. while(account[from] < amount) usleep(10000);
  54. t = account[from];
  55. t = t-amount;
  56. account[from] = t;
  57. t = account[to];
  58. t = t+amount;
  59. account[to] = t;
  60. usleep(10);
  61. ntrans++;
  62. if(ntrans % 1000==0) test();
  63. }
  64. void* ThreadProc(int *arg)
  65. {
  66. int from;
  67. from = *arg;
  68. while(1)
  69. {
  70. srand((unsigned)time(NULL));
  71. int to = (int)(NCNT*(rand()/(RAND_MAX+1, 0)));
  72. if(to==NCNT) to = 0;
  73. if(to==from) to = (to+1)%NCNT;
  74. int amount = 1+(int)( (INIT_BANK*(rand()/(RAND_MAX+1, 0)))/2 );
  75. transfer(from, to, amount);
  76. }
  77. return;
  78. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注