c - Linux scheduling. (pthreads) -


i'm trying play around threads , far, code below, i'm doing fine. want want print current index of executing thread i've encountered problems.

#include <pthread.h> #include <stdio.h> #define num_threads 5  void *runner(void *param);  int main(int argc, char *argv[]) {     int i, policy;     pthread_t tid[num_threads];     pthread_attr_t attr;      pthread_attr_init(&attr);      if(pthread_attr_getschedpolicy(&attr, &policy) != 0)         fprintf(stderr, "unable policy.\n");     else{         if(policy == sched_other)             printf("sched_other\n");         else if(policy == sched_rr)             printf("sched_rr\n");         else if(policy == sched_fifo)             printf("sched_fifo\n");     }      if(pthread_attr_setschedpolicy(&attr, sched_fifo) != 0)         fprintf(stderr, "unable set policy.\n");     /* create threads */     for(i = 0; < num_threads; i++)         printf("hi, i'm thread #%d\n", i);         pthread_create(&tid[i], &attr, runner, null);     /* join on each thread */     for(i = 0; < num_threads; i++)         pthread_join(tid[i], null); }  /* each thread begin control in function */ void *runner(void *param) {      /* work... */      printf("hello world!");      pthread_exit(0); } 

i'm trying print current executing thread along "hello world!". but, output this...

sched_other hello, i'm thread #0 hello, i'm thread #1 hello, i'm thread #2 hello, i'm thread #3 hello, i'm thread #4 segmentation fault (core dumped) 

so far, i've tried issuing

ulimit -c unlimited 

what can tweak in code achieve goal?

you forgot put block of statements in braces:

for(i = 0; < num_threads; i++)     printf("hi, i'm thread #%d\n", i);     pthread_create(&tid[i], &attr, runner, null); 

multiple statements executed in loop must covered in braces otherwise first of them called, printf("hi, i'm thread #%d\n", i) in case. solution:

for(i = 0; < num_threads; i++) {     printf("hi, i'm thread #%d\n", i);     pthread_create(&tid[i], &attr, runner, null); } 

Comments