I'm quite new to multi-threading programming. I want to write a code with 3 different threads, each of which prints some different characters. The execution of the threads should be based on a round-robin algorithm. Suppose we have t1, t2, and t3 threads, their execution sequence should be like t1, t2, t3, t1, t2, t3,...
I write the following code for this purpose:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sched.h>
void* a(void* ptr) {
for (int i=0; i< 10; i++){
printf("1");
printf("2");
printf("3");
printf("4");
}
return NULL;
}
void* b(void* ptr) {
for (int i=0; i< 10; i++){
printf("a");
printf("b");
printf("c");
printf("d");
}
return NULL;
}
void* c(void* ptr) {
for (int i=0; i< 10; i++){
printf("5");
printf("6");
printf("7");
printf("8");
}
return NULL;
}
int main() {
pthread_attr_t attr1, attr2, attr3;
pthread_attr_init(&attr1);
pthread_attr_init(&attr2);
pthread_attr_init(&attr3);
pthread_t t1, t2, t3;
pthread_attr_setschedpolicy(&attr1, SCHED_RR);
pthread_create(&t1, &attr1, a, NULL);
pthread_attr_setschedpolicy(&attr2, SCHED_RR);
pthread_create(&t2, &attr2, b, NULL);
pthread_attr_setschedpolicy(&attr3, SCHED_RR);
pthread_create(&t3, &attr3, c, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_exit(0);
return 0;
}
And the output is:
First of all: the output is not reproducible, every time I run the binary file I get different output.
12341234123412341234156785678567856785678567856785678567856782341234123412341234abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd
.
My desired output is something like this:
123abc567...
Does everybody know what the problem is with my code?
Thanks