簡體   English   中英

多線程標准輸出在每次執行時的寫入方式不同

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

每次我運行以下代碼時,它似乎都是隨機執行的,我不理解為什么有時它會打印某些行而在其他時候卻不打印。

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);
}

這是七個連續執行的輸出:

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

您的主線程不在等待子線程退出。 退出主線程也會殺死所有子線程。 因此,這是一個競爭條件,因此最終的行為是不確定的。

main添加一個pthread_join調用,以等待子線程退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM