#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#define NUM_THREADS 3 //number of threads
void* thread_function(void* arg)
{
int thread_id = *((int*)arg);
int i=0;
while(i<2)//each thread executes only once.//change this '1' to any values for multiple time execution
{
i++;
}
printf("Thread %d is running.\n", thread_id
); return NULL;
}
int main()
{
pthread_t threads[NUM_THREADS];
pthread_attr_t attr[NUM_THREADS];
struct sched_param param[NUM_THREADS];
int thread_ids[NUM_THREADS] = {0, 1, 2};
// Initialize attributes and create threads with round-robin scheduling
for (int i = 0; i < NUM_THREADS; i++)
{
pthread_attr_init(&attr[i]);
// Set scheduling policy to SCHED_RR
// int policy = SCHED_RR; //round robin scheduling
int policy = SCHED_FIFO; // first in first out scheduling
// int policy = SCHED_OTHER; // uses any other scheduling algorithm
// int policy = SCHED_SPORADIC; //sporadic scheduling algorithm
pthread_attr_setschedpolicy(&attr[i], policy);
// param[i].sched_priority = 10 + i; // Assign different priorities (10, 11, 12)
// pthread_attr_setschedparam(&attr[i], ¶m[i]);// assign priorities for priority based scheduling
// Create the thread
if (pthread_create(&threads[i], &attr[i], thread_function, &thread_ids[i]) != 0)
{
return EXIT_FAILURE;
}
}
for (int i = 0; i < NUM_THREADS; i++)
{
pthread_join(threads[i], NULL);
pthread_attr_destroy(&attr[i]); // Clean up attributes
}
printf("All threads have finished.\n"); return 0;
}
I2luY2x1ZGUgPHB0aHJlYWQuaD4KI2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHNjaGVkLmg+CgojZGVmaW5lIE5VTV9USFJFQURTIDMgIC8vbnVtYmVyIG9mIHRocmVhZHMKCnZvaWQqIHRocmVhZF9mdW5jdGlvbih2b2lkKiBhcmcpCnsKICAgIGludCB0aHJlYWRfaWQgPSAqKChpbnQqKWFyZyk7CiAgICBpbnQgaT0wOwogICAgd2hpbGUoaTwyKS8vZWFjaCB0aHJlYWQgZXhlY3V0ZXMgb25seSBvbmNl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