Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding parallel POSIX threads

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;

}
like image 580
Granolaboy Avatar asked Jan 11 '23 16:01

Granolaboy


1 Answers

You can't rely on timing assumptions when multithreading.

An explanation for this question is that the sequence of printfs inside your loop take so little time to execute that can be executed inside the quantum of time given to the thread.

like image 73
Paulo Bu Avatar answered Jan 21 '23 16:01

Paulo Bu