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

输出:

相关推荐
牛马大师兄35 分钟前
数据结构复习 | 循环链表
c语言·数据结构·c++·笔记·链表
xyq202437 分钟前
Scala 提取器(Extractor)
开发语言
林姜泽樾40 分钟前
centOS改中文输入法教程
linux·运维·服务器·centos
A懿轩A40 分钟前
【Java 基础编程】Java 正则表达式实战:Pattern/Matcher、元字符与常用正则,验证与提取必备
java·开发语言·正则表达式
小杰帅气43 分钟前
POSIX信号量
linux·运维·服务器
微风◝44 分钟前
网络安全入门系列(1):VMware安装Kali Linux 2025.4
linux·运维·服务器
zh_xuan1 小时前
kotlin with函数
开发语言·kotlin
Eternity∞1 小时前
数据结构基础
c语言·开发语言·数据结构·学习·vim
柒.梧.1 小时前
Java代理模式精讲:静态代理+JDK动态代理
java·开发语言·代理模式
智塑未来1 小时前
卫星在轨运行5年以上用什么品牌SSD寿命够?航天级存储的长寿命保障技术解析
开发语言·javascript·数据库