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

输出:

相关推荐
Fu2067219 小时前
第一阶段项目
linux·服务器·网络
Navigator_Z12 小时前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
yiangL_12 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
geovindu14 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk816315 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
敲上瘾15 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
女神下凡16 小时前
芯参谋(119):凌阳(Sunplus)_开发指南
linux·arm开发·stm32·单片机·嵌入式硬件
炸膛坦客16 小时前
单片机/C/C++八股:(三十三)取别名
c语言·c++·单片机
听情歌落俗16 小时前
嵌入式学习1-C语言基础语法与STM32实践
c语言·开发语言
小飞在努力17 小时前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端