《操作系统》的实验代码。

84 рядки
1.7 KiB

12 роки тому
  1. #include <ulib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #define MATSIZE 10
  6. static int mata[MATSIZE][MATSIZE];
  7. static int matb[MATSIZE][MATSIZE];
  8. static int matc[MATSIZE][MATSIZE];
  9. void
  10. work(unsigned int times) {
  11. int i, j, k, size = MATSIZE;
  12. for (i = 0; i < size; i ++) {
  13. for (j = 0; j < size; j ++) {
  14. mata[i][j] = matb[i][j] = 1;
  15. }
  16. }
  17. yield();
  18. cprintf("pid %d is running (%d times)!.\n", getpid(), times);
  19. while (times -- > 0) {
  20. for (i = 0; i < size; i ++) {
  21. for (j = 0; j < size; j ++) {
  22. matc[i][j] = 0;
  23. for (k = 0; k < size; k ++) {
  24. matc[i][j] += mata[i][k] * matb[k][j];
  25. }
  26. }
  27. }
  28. for (i = 0; i < size; i ++) {
  29. for (j = 0; j < size; j ++) {
  30. mata[i][j] = matb[i][j] = matc[i][j];
  31. }
  32. }
  33. }
  34. cprintf("pid %d done!.\n", getpid());
  35. exit(0);
  36. }
  37. const int total = 21;
  38. int
  39. main(void) {
  40. int pids[total];
  41. memset(pids, 0, sizeof(pids));
  42. int i;
  43. for (i = 0; i < total; i ++) {
  44. if ((pids[i] = fork()) == 0) {
  45. srand(i * i);
  46. int times = (((unsigned int)rand()) % total);
  47. times = (times * times + 10) * 100;
  48. work(times);
  49. }
  50. if (pids[i] < 0) {
  51. goto failed;
  52. }
  53. }
  54. cprintf("fork ok.\n");
  55. for (i = 0; i < total; i ++) {
  56. if (wait() != 0) {
  57. cprintf("wait failed.\n");
  58. goto failed;
  59. }
  60. }
  61. cprintf("matrix pass.\n");
  62. return 0;
  63. failed:
  64. for (i = 0; i < total; i ++) {
  65. if (pids[i] > 0) {
  66. kill(pids[i]);
  67. }
  68. }
  69. panic("FAIL: T.T\n");
  70. }