I’m trying to play around with threads and so far, with the code below, I’m doing fine. I want also want to print the current index of the executing thread but I’ve encountered some problems.
JavaScript
x
#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 to get policy.n");
else{
if(policy == SCHED_OTHER)
printf("SCHED_OTHERn");
else if(policy == SCHED_RR)
printf("SCHED_RRn");
else if(policy == SCHED_FIFO)
printf("SCHED_FIFOn");
}
if(pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0)
fprintf(stderr, "Unable to set policy.n");
/* create the threads */
for(i = 0; i < NUM_THREADS; i++)
printf("Hi, I'm thread #%dn", i);
pthread_create(&tid[i], &attr, runner, NULL);
/* now join on each thread */
for(i = 0; i < NUM_THREADS; i++)
pthread_join(tid[i], NULL);
}
/* Each thread will begin control in this function */
void *runner(void *param)
{
/* do some work... */
printf("Hello world!");
pthread_exit(0);
}
I’m trying to print the current executing thread along with “Hello world!”. But, the output is this…
JavaScript
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 already tried issuing
JavaScript
ulimit -c unlimited
What can I tweak in the code to achieve my goal?
Advertisement
Answer
You forgot to put a block of statements in braces:
JavaScript
for(i = 0; i < NUM_THREADS; i++)
printf("Hi, I'm thread #%dn", i);
pthread_create(&tid[i], &attr, runner, NULL);
Multiple statements to be executed in for loop must be covered in braces otherwise only first of them is called, printf("Hi, I'm thread #%dn", i)
in this case. Solution:
JavaScript
for(i = 0; i < NUM_THREADS; i++)
{
printf("Hi, I'm thread #%dn", i);
pthread_create(&tid[i], &attr, runner, NULL);
}