我想创建两个线程,它们看起来像这样:
P1:
while(1) {
printf("1");
printf("2");
printf("3");
printf("4");
}
return NULL;
Run Code Online (Sandbox Code Playgroud)
P2:
while(1) {
printf("5");
printf("6");
printf("7");
printf("8");
}
return NULL;
Run Code Online (Sandbox Code Playgroud)
根据我对并行线程的了解,它不会打印12345678,而是由于缺少同步而导致数字的完全随机变化.
然而,当我尝试在实际代码中复制它时,它会继续打印1234几次,然后切换到5678,打印几次并返回到1234.
我对线程的理解是错误的还是我的代码不等同于问题?
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;
}
Run Code Online (Sandbox Code Playgroud)