多线程编程简单例题(pthread) Linux环境 C语言实现

问题: 编写程序完成如下功能:
1> open一个文件
2> 创建一个新线程(记得将描述符传给线程入口函数)
3> 新线程向文件里写入"abc"
4> 主线程向文件里写入"def"
要求确保文件内容为"abcdef"


pthread_create ( )

pthread_join( )


代码:

cpp 复制代码
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

void *func(void *parg){
    int fd = (int)(long)parg;
    write(fd,"abc",3);
    return (void*)(long)199; // 返回值测试,先强转成long型(8字节),再强转成void*
}

int main(int argc,char *argv[]){
    int fd = -1;
    pthread_t threadId; // threadId
    int ret = 0;
    void* s=NULL; // 存储返回值

    fd = open("test.txt",O_RDWR | O_CREAT | O_TRUNC,0666); // open file
    if(fd < 0){
        printf("w-open %s failed\n","test.txt");
        return 1;
    }
    ret = pthread_create(&threadId, NULL, func, (void*)(long)fd); // pthread_create()
    if(ret){
        close(fd);
        fd = -1;
        printf("pthread_create failed.\n");
        return 2;
    }
    pthread_join(threadId,&s); // pthread_join()
    printf("%ld\n",threadId);
    printf("%d\n",(int)(long)s); // test return value

    write(fd,"def",3);
    close(fd);
    fd = -1;
    return 0;
}

输出:

相关推荐
niuTaylor几秒前
飞腾 FT-2000/4 Ubuntu 内存卡 / NVMe SSD 系统制作完整指南
linux·服务器·人工智能·驱动开发·单片机
思茂信息41 分钟前
CST软件BCI仿真模型及仿真案例
开发语言·单片机·嵌入式硬件·算法·emc
阿里嘎多学长1 小时前
2026-09-28 GitHub 热点项目精选
开发语言·程序员·github·代码托管
傲世仙尊1 小时前
信号量环形队列与线程池起步-把临界资源拆成很多份
linux
小小龙学IT1 小时前
三菱 PLC MC 协议(SLMP / QnA 兼容 3E 帧)深度解析:从帧结构到 C++/Go 双语言采集实战
c语言·c++·golang
Huangjin007_1 小时前
【Linux 系统篇(二十五)】文件(二) 系统文件I/O详解
linux·运维·服务器
Logic1011 小时前
C语言/数据结构位运算题解:异或XOR找出游戏速通中的“独特初始能量值“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
程序猿编码1 小时前
C++/CUDA 手写 LLM 推理引擎:拆解 vLLM 核心 PagedAttention 与连续批处理
开发语言·c++·深度学习·神经网络·推理·vllm
hold?fish:palm2 小时前
44 二叉搜索树中第K小的元素
开发语言·c++·算法
ShineWinsu2 小时前
对于ProtoBuffer:ProtoBuffer的介绍以及安装
linux·网络·google·协议·序列化·反序列化·protobuffer