多线程编程简单例题(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;
}

输出:

相关推荐
黄贵根24 分钟前
JavaScript实现教培行业意向登记系统
开发语言·javascript·ecmascript
zzzll11113 小时前
Claude Code离线安装方案揭秘
开发语言·php
ltl4 小时前
纠删码原理与存储效率
linux
ltl4 小时前
MinIO 原理和架构:机制、AGPL 与上游 archived 风险
linux
wling03014 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
林浩杨_4 小时前
linux搜索命令(grep+sed)
linux·命令模式
郝学胜-神的一滴4 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
W.W.H.4 小时前
将驱动编译成模块并安装到rootfs
linux·物联网·wifi·rootfs·驱动
ltl4 小时前
io_uring 在生产环境翻车实录:内核 bug、资源泄漏和你不知道的限制
linux
ltl4 小时前
内存分配器擂台:jemalloc vs tcmalloc vs mimalloc vs glibc
linux