c - 为什么第二个函数没有运行和/或产生输出? (Linux 中的 C)

标签 c linux macos pthreads mutex

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>             //needed for Mac Linux

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Declares Mutex Lock Globally

void* print_i(void *ptr)
{
        pthread_mutex_lock(&mutex); //ensures whole function gets executed without interleaving

        printf("1: I am \n");
        sleep(1);               //program to pause for 1 sec
        printf("in i\n");
        return NULL;            //needed b/c function does not return anything

        pthread_mutex_unlock(&mutex); //releases function to continue rest of program
}

void* print_j(void *ptr)
{
        pthread_mutex_lock(&mutex); //ensures whole function gets executed without interleaving

        printf("2: I am \n");
        sleep(1);               //program to pause for 1 sec
        printf("in j\n");
        return NULL;            //needed b/c function does not return anything

        pthread_mutex_unlock(&mutex); //releases function to continue rest of program
}

int main()
{
        pthread_t t1,t2;
        int rc1 = pthread_create(&t1, NULL, print_i, NULL);
        int rc2 = pthread_create(&t2, NULL, print_j, NULL);
        pthread_join(t1, NULL); //allows functions to iterate completely(T1,T2,Main,T1,T2,Main..)
        pthread_join(t2, NULL); //allows functions to iterate completely(T1,T2,Main,T1,T2,Main..)

        exit(0);
}

我们应该得到以下结果:

1: I am/n
in I/n
2: I am/n
in j/n

我的输出实际上是:

1: I am
in i

在我的实际输出之后,我似乎被“卡在”程序中了。例如,向上箭头生成“^[[A”。任何帮助我们找出为什么没有达到预期结果的帮助将不胜感激。我使用的是 M1 MacBook Pro。

最佳答案

return语句之后的下一个语句没有获得控制权

    return NULL;            //needed b/c function does not return anything

    pthread_mutex_unlock(&mutex); 

因此互斥体未解锁。

关于c - 为什么第二个函数没有运行和/或产生输出? (Linux 中的 C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75837500/

相关文章:

c - 是否可以修改 Dymola 的编译器包含路径?

linux - 从哪里获得适用于 Linux 的 msbuild

macos - OS X 应用程序无需激活即可运行?

python-3.x - 无法获取 pip 在 mac 10.13 python 3.11 上安装 wordcloud

c - 在 C 中将 sigaction 与计时器一起使用时遇到问题

在c中创建动态二维Char数组

linux - Unix:过滤和操作 CSV 中的列数据

linux - 使用 Perl 从文件中读取特定列值

javascript - 在 Chrome/Mac 上强制 DOM 重绘/刷新

C 跳过函数的一个命令?