You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

操作系统作业C语言pthread代码在Mac终端运行失败问题求助

问题原因与解决方法

代码本身存在的问题

  • 线程执行函数缺少返回值:你定义的print_i和print_j返回值类型是void*,但函数体内没有写return语句,属于语法不规范,部分编译器会直接报错。
  • 主进程提前退出:pthread_create仅负责启动线程,主线程不会自动等待子线程执行完成,你在创建完线程后直接调用exit(0)会直接终止整个进程,两个子线程大概率还没来得及执行就被销毁,会导致运行异常。

Mac系统编译注意事项

Mac的clang编译器编译pthread相关代码时,需要显式指定链接pthread库,编译指令要加-lpthread参数,否则会出现链接报错。

修改后完整代码

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

// 两个并发执行的函数
void* print_i(void *ptr)
{
    printf("I am in i\n");
    return NULL;
}
void* print_j(void *ptr)
{
    printf("I am in j\n");
    return NULL;
}
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);
    pthread_join(t2, NULL);
    exit(0);
}

编译运行指令

替换your_code.c为你实际的代码文件名,执行以下指令编译:
clang your_code.c -o pthread_demo -lpthread
编译完成后运行生成的可执行文件即可:
./pthread_demo

内容的提问来源于stack exchange,提问作者BennyBen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 22:15:01