multisleep.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #define _GNU_SOURCE
  2. #include <sched.h>
  3. #include <signal.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <sys/types.h>
  8. #include <sys/wait.h>
  9. #include <unistd.h>
  10. #define SLEEP_TIME 10
  11. #define FIBER_STACK (1024 * 64)
  12. int proc;
  13. int thread_function(void* arg) {
  14. int thread = (int)((unsigned long)arg);
  15. printf("in process %d thread %d\n", proc, thread);
  16. for (int i = 0; i < SLEEP_TIME; i++) {
  17. printf("in process %d thread %d: %d\n", proc, thread, i);
  18. sleep(1);
  19. }
  20. return 0;
  21. }
  22. int main(int argc, char** argv) {
  23. int nprocs = 1, nthreads = 1;
  24. int thread;
  25. setvbuf(stdout, NULL, _IONBF, 0);
  26. for (int i = 1; i < argc; i++) {
  27. if (!strcmp(argv[i], "-n") && i + 1 < argc) {
  28. nprocs = atoi(argv[i + 1]);
  29. i++;
  30. continue;
  31. }
  32. if (!strcmp(argv[i], "-t") && i + 1 < argc) {
  33. nthreads = atoi(argv[i + 1]);
  34. i++;
  35. continue;
  36. }
  37. }
  38. for (proc = nprocs; proc > 1; proc--) {
  39. int ret = fork();
  40. if (ret < 0) {
  41. perror("fork");
  42. _exit(1);
  43. }
  44. if (!ret)
  45. break;
  46. }
  47. for (thread = 1; thread < nthreads; thread++) {
  48. void* stack = malloc(FIBER_STACK);
  49. if (!stack) {
  50. perror("malloc: could not allocate stack");
  51. _exit(1);
  52. }
  53. clone(&thread_function, (void*)stack + FIBER_STACK,
  54. CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM,
  55. (void*)((unsigned long)thread + 1));
  56. }
  57. for (int i = 0; i < SLEEP_TIME; i++) {
  58. printf("in process %d thread 1: %d\n", proc, i);
  59. sleep(1);
  60. }
  61. return 0;
  62. }