简体   繁体   English

多线程标准输出在每次执行时的写入方式不同

[英]Multi-threading stdout write differently on every execution

Every time I run the following code it executes seemingly random, and I'm not understanding why sometimes it prints certain lines and at other times it does not. 每次我运行以下代码时,它似乎都是随机执行的,我不理解为什么有时它会打印某些行而在其他时候却不打印。

Compiled with clang -Wall -lpthread test.c clang -Wall -lpthread test.c编译

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

int var = 2;
pthread_t my_thread;
pthread_mutex_t lock;

void* thread_func(void *args);
void thread_func2();

void* thread_func(void *args) {
    pthread_mutex_lock(&lock);
    printf("Entered thread_func\n");
    fflush(stdout);
    pthread_mutex_unlock(&lock);

    thread_func2();

    pthread_mutex_lock(&lock);
    printf("Exiting thread_func\n");
    fflush(stdout);
    pthread_mutex_unlock(&lock);
    return NULL;
}

void thread_func2() {
    pthread_mutex_lock(&lock);
    printf("Entering thread_func2\n");
    fflush(stdout);
    pthread_mutex_unlock(&lock);

    for(int i = 0; i < var; i++) {
        pthread_mutex_lock(&lock);
        printf("Var = %d.\n", i);
        fflush(stdout);
        pthread_mutex_unlock(&lock);
    }

    pthread_mutex_lock(&lock);
    printf("Exiting thread_func2\n");
    fflush(stdout);
    pthread_mutex_unlock(&lock);
}

int main(int argc, char** argv) {
    int status;
    status = pthread_create(&my_thread, NULL, thread_func, NULL);

    pthread_mutex_lock(&lock);
    printf("Status = %d\n", status);
    pthread_mutex_unlock(&lock);
}

Here's the output from seven consecutive executions: 这是七个连续执行的输出:

ssh.server.connected.to 219% a.out
Status = 0
Entered thread_func
Entered thread_func
Entering thread_func2
Var = 0.
Var = 1.
Exiting thread_func2
Exiting thread_func2
Exiting thread_func

ssh.server.connected.to 220% a.out
Status = 0
Entered thread_func
Entered thread_func

ssh.server.connected.to 221% a.out
Status = 0
Entered thread_func
Entered thread_func

ssh.server.connected.to 222% a.out
Status = 0
Entered thread_func
Entered thread_func

ssh.server.connected.to 223% a.out
Status = 0
Entered thread_func
Entered thread_func

ssh.server.connected.to 224% a.out
Status = 0
Entered thread_func
Entered thread_func

ssh.server.connected.to 225% a.out
Status = 0
Entered thread_func

Your main thread is not waiting for the child thread to exit. 您的主线程不在等待子线程退出。 Exiting the main thread will also kill all the child threads. 退出主线程也会杀死所有子线程。 So it's a race condition and thus the resulting behaviour is non-deterministic. 因此,这是一个竞争条件,因此最终的行为是不确定的。

Add a pthread_join call in main to wait for the child thread to exit. main添加一个pthread_join调用,以等待子线程退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM