multisleep.c 1.9 KB

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