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

输出:

相关推荐
醇氧1 小时前
【Windows】优雅启动:解析一个 Java 服务的后台启动脚本
java·开发语言·windows
石像鬼₧魂石1 小时前
如何配置Fail2Ban的Jail?
linux·学习·ubuntu
椰子今天很可爱2 小时前
五种I/O模型与多路转接
linux·c语言·c++
MapGIS技术支持2 小时前
MapGIS Objects Java计算一个三维点到平面的距离
java·开发语言·平面·制图·mapgis
Lueeee.2 小时前
Linux kernel Makefile 语法
linux
程序员zgh3 小时前
C++ 互斥锁、读写锁、原子操作、条件变量
c语言·开发语言·jvm·c++
小灰灰搞电子3 小时前
Qt 重写QRadioButton实现动态radioButton源码分享
开发语言·qt·命令模式
by__csdn3 小时前
Vue3 setup()函数终极攻略:从入门到精通
开发语言·前端·javascript·vue.js·性能优化·typescript·ecmascript
喵了meme3 小时前
C语言实战5
c语言·开发语言
廋到被风吹走4 小时前
【Java】常用设计模式及应用场景详解
java·开发语言·设计模式