fork download
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sched.h>
  5.  
  6. #define NUM_THREADS 3 //number of threads
  7.  
  8. void* thread_function(void* arg)
  9. {
  10. int thread_id = *((int*)arg);
  11. int i=0;
  12. while(i<2)//each thread executes only once.//change this '1' to any values for multiple time execution
  13. {
  14. printf("id=%d\n", thread_id);
  15. i++;
  16. }
  17.  
  18. printf("Thread %d is running.\n", thread_id);
  19. return NULL;
  20. }
  21.  
  22. int main()
  23. {
  24. pthread_t threads[NUM_THREADS];
  25. pthread_attr_t attr[NUM_THREADS];
  26. struct sched_param param[NUM_THREADS];
  27. int thread_ids[NUM_THREADS] = {0, 1, 2};
  28.  
  29. // Initialize attributes and create threads with round-robin scheduling
  30. for (int i = 0; i < NUM_THREADS; i++)
  31. {
  32. pthread_attr_init(&attr[i]);
  33.  
  34. // Set scheduling policy to SCHED_RR
  35. // int policy = SCHED_RR; //round robin scheduling
  36. int policy = SCHED_FIFO; // first in first out scheduling
  37. // int policy = SCHED_OTHER; // uses any other scheduling algorithm
  38. // int policy = SCHED_SPORADIC; //sporadic scheduling algorithm
  39. pthread_attr_setschedpolicy(&attr[i], policy);
  40.  
  41. // param[i].sched_priority = 10 + i; // Assign different priorities (10, 11, 12)
  42. // pthread_attr_setschedparam(&attr[i], &param[i]);// assign priorities for priority based scheduling
  43.  
  44. // Create the thread
  45. if (pthread_create(&threads[i], &attr[i], thread_function, &thread_ids[i]) != 0)
  46. {
  47. perror("pthread_create");
  48. return EXIT_FAILURE;
  49. }
  50. }
  51.  
  52. for (int i = 0; i < NUM_THREADS; i++)
  53. {
  54. pthread_join(threads[i], NULL);
  55. pthread_attr_destroy(&attr[i]); // Clean up attributes
  56. }
  57.  
  58. printf("All threads have finished.\n");
  59. return 0;
  60. }
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
id=2
id=2
Thread 2 is running.
id=1
id=1
Thread 1 is running.
id=0
id=0
Thread 0 is running.
All threads have finished.