C 对于线程中的循环,创建终止,不打印任何内容

C 对于线程中的循环,创建终止,不打印任何内容,c,C,线程_create中的for循环终止,不打印任何内容。 当我在gdb中调试时,观察新线程立即终止。 我不知道为什么 #include <pthread.h> #include <stdio.h> #include <unistd.h> void* myturn(void * arg){ for(int j; ; j++){ sleep(3); fprintf(stderr, "my turn\n"

线程_create中的for循环终止,不打印任何内容。 当我在gdb中调试时,观察新线程立即终止。 我不知道为什么

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

void* myturn(void * arg){
    for(int j; ; j++){
         sleep(3);
        fprintf(stderr, "my turn\n");
        printf("my turn\n");
        //pthread_exit(0);
    }
    sleep(3);
    return NULL;
}

int yourturn(){
    for(int i; i<3; i++){
        sleep(2);
        printf("your turn\n");
    }
}

int main(int arg, char * argv[]){
    pthread_t new_thread;
    pthread_create(&new_thread, NULL, myturn, NULL);
    // myturn();
    yourturn();
    pthread_join(new_thread, NULL);
    return 0;
}
#包括
#包括
#包括
void*myturn(void*arg){
for(int j;;j++){
睡眠(3);
fprintf(stderr,“轮到我了”);
printf(“轮到我了”);
//pthread_退出(0);
}
睡眠(3);
返回NULL;
}
int yourturn(){

对于(inti;i我对您的代码进行了一些修改,并对其工作原理进行了说明:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>


void* myturn(void * arg){
    
    int j = 0;
    for(j=0; j<10; j++){
         sleep(1);
        fprintf(stderr, "my turn\n");
        printf("my turn\n");
        //pthread_exit(0);
         
    }
    sleep(1);
    return NULL;
}

int yourturn(){
    int i = 0;
    for(i=0; i<30; i++){
        sleep(2);
        printf("your turn\n");
    }

}

int main(int arg, char * argv[]){
    pthread_t new_thread;
    pthread_create(&new_thread, NULL, myturn, NULL);
    // myturn();
    yourturn();
    pthread_join(new_thread, NULL);
    return 0;
}

  • <代码> >(int i;i 尝试初始化循环变量i和j为零或某物。< /p>您没有初始化for for循环变量,因此程序有未定义的行为。它没有线程吗?这只是C代码,所以如果您实际使用C++,请说明。
     for(int j; ; j++){
    
     for(int i; i<3; i++){