简体   繁体   中英

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

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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