#define _GNU_SOURCE #include #include #include #include #include typedef struct { int id; unsigned long sleep_ms; }ThreadParams; void *workAndSleep(void * par) { ThreadParams *th_param = (ThreadParams*)par; usleep(500000); while (1) { printf("THREAD %d : Running \n", th_param->id); /* Il thread entra in un lungo CPU-burst, saturando la CPU */ int i=0; for(i=0; i<100000000; i++) { /* Ogni tanto notifica a video dov'è arrivato (chiamando una syscall) */ if (!(i%20000000)) printf("THREAD %d : i = %d\n",th_param->id,i); } printf("THREAD %d : Sleep\n\n",th_param->id); /* Si ferma per qualche istante (chiamando una syscall) */ usleep( th_param->sleep_ms * 1000 ); } pthread_exit(NULL); } int main(int argc,char **argv) { /* Setta priorità 99 e scheduler FIFO per il processo padre */ /* struct sched_param schp;; memset(&schp,0,sizeof(schp)); schp.sched_priority = 99; if(sched_setscheduler(0, SCHED_FIFO, &schp)) { fprintf(stderr, "\n**********************ALERT**********************\n"); fprintf(stderr, "Unable to get realtime scheduling priority.\n"); fprintf(stderr, "This is BAD if you are trying to capture data.\n"); fprintf(stderr, "To enable realtime scheduling, add yourself to rtprio=100 and nice=-20 \n"); fprintf(stderr, "in /etc/security/limits.conf \n"); } */ pthread_t thread1, thread2, thread3, thread4; ThreadParams tp1 = {1,3000}, tp2 = {2,3000}, tp3 = {3,1000}, tp4 = {4,1000}; pthread_attr_t attr; struct sched_param param; memset(¶m,0,sizeof(param)); pthread_attr_init(&attr); /* Assicuro che il thread possa essere sechedulato * con gli scheduler realtime FIFO e RR */ pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setinheritsched(&attr,PTHREAD_EXPLICIT_SCHED); /* Impongo che thread siano eseguiti su di una sola CPU */ cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(0, &cpuset); pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset); /* Setto priorità 99 e tipo di scheduler FIFO * (utilizzate per i thread 1 e 2) */ param.sched_priority = 99; pthread_attr_setschedpolicy(&attr, SCHED_FIFO); pthread_attr_setschedparam(&attr, ¶m); /* Lancio i thread 1 e 2 */ pthread_create(&thread1, &attr, workAndSleep, &tp1); pthread_create(&thread2, &attr, workAndSleep, &tp2); /* Setto priorità 98 e il tipo di scheduler RR * (utilizzate per i thread 3 e 4) */ param.sched_priority = 98; pthread_attr_setschedpolicy(&attr, SCHED_RR); pthread_attr_setschedparam(&attr, ¶m); /* Lancio i thread 3 e 4 */ pthread_create(&thread3, &attr, workAndSleep, &tp3); pthread_create(&thread4, &attr, workAndSleep, &tp4); /* Attendo la terminazione di tutti i thread * (in realtà i thread non terminano)*/ pthread_join(thread1,NULL); pthread_join(thread2,NULL); pthread_join(thread3,NULL); pthread_join(thread4,NULL); pthread_exit(NULL); }