gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:13:05 25 4
gpt4 key购买 nike

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

非常感谢

使用 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;
}

最佳答案

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

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

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

关于c - 使用互斥量时 stdout 中没有输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33431359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com