multisleep.c 1.7 KB

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