I want to create two threads, which are supposed to look like this:
P1:
while(1) {
printf("1");
printf("2");
printf("3");
printf("4");
}
return NULL;
P2:
while(1) {
printf("5");
printf("6");
printf("7");
printf("8");
}
return NULL;
According to my knowledge of parallel threads it won't print 12345678 but a completely random variation of the numbers due to lack of synchronization.
However when I try to replicate it in real code it keeps printing 1234 a few times, then switches to 5678, prints it a few times and goes back to 1234.
Is my understanding of threads wrong or is my code not equivalent to the problem?
void *print1(void *arg) {
while(1) {
printf("1");
printf("2");
printf("3");
printf("4\n");
}
return NULL;
}
void *print2(void *arg) {
while(1){
printf("5");
printf("6");
printf("7");
printf("8\n");
}
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, print1, NULL);
pthread_create(&tid2, NULL, print2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}