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

输出:

相关推荐
lixzest几秒前
Vim 快捷键速查表
linux·编辑器·vim
草莓熊Lotso几秒前
Qt 进阶核心:UI 开发 + 项目解析 + 内存管理实战(从 Hello World 到对象树)
运维·开发语言·c++·人工智能·qt·ui·智能手机
2501_941865636 分钟前
从事件驱动到异步架构的互联网工程语法构建与多语言实践分享
java·开发语言·jvm
前端 贾公子3 小时前
v-if 与 v-for 的优先级对比
开发语言·前端·javascript
嗯嗯=4 小时前
python学习篇
开发语言·python·学习
ICscholar6 小时前
ExaDigiT/RAPS
linux·服务器·ubuntu·系统架构·运维开发
sim20206 小时前
systemctl isolate graphical.target命令不能随便敲
linux·mysql
不会c嘎嘎7 小时前
QT中的常用控件 (二)
开发语言·qt
是一个Bug7 小时前
50道核心JVM面试题
java·开发语言·面试
米高梅狮子7 小时前
4. Linux 进程调度管理
linux·运维·服务器