使用互斥量时 stdout 中没有输出

No output in stdout when using mutex

有人知道如何记录数据吗?它有时会打印一些东西,但大多数时候什么都不打印。我不知道,错误在哪里...也尝试过不使用互斥锁,但它仍然不起作用。

非常感谢

编译为 gcc -o testtest.c -std=c99 -Wall -Wextra -pedantic -pthread

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

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void logger(const char *msg) {
    pthread_mutex_lock(&lock);
    printf("%s", msg);
    fflush(stdout);
    pthread_mutex_unlock(&lock);
}

void *A(void *arg) {
    fprintf(stderr, "AAA");
    logger("Inside thread A");
    return NULL;
}

void *B(void *arg) {
    fprintf(stderr, "BBB");
    logger("Inside thread A");
    return NULL;
}

pthread_t t_id[2];

int main() {
    int s1 = pthread_create(&(t_id[0]), NULL, &A, NULL);
    int s2 = pthread_create(&(t_id[1]), NULL, &B, NULL);

    if (s1 || s2) {
        perror("ERROR: Create thread");
        exit(2);
    }

    // EDIT; THIS WAS MISSING
    pthread_join(t_id[0], NULL);
    pthread_join(t_id[1], NULL);

    return 0;
}

重复@πìντα ῥεῖ 所说的内容。

您需要加入您的线程,或等待所有线程完成执行后再退出应用程序。

否则应用程序会在线程有机会打印消息之前退出。