【问题标题】:No output in stdout when using mutex使用互斥锁时标准输出中没有输出
【发布时间】:2015-10-30 08:12:53
【问题描述】:

有人知道如何记录数据吗?它有时会打印一些东西,但几乎什么也没有。我不知道,哪里是一个错误......也尝试过不使用互斥锁,但它仍然无法正常工作。

非常感谢

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

【问题讨论】:

  • 你忘记加入main()的话题了。
  • 哇,傻我:D,谢谢

标签: c linux multithreading pthreads


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2012-04-26
    相关资源
    最近更新 更多