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

输出:

相关推荐
xiaoye37085 小时前
Java 自动装箱 / 拆箱 原理详解
java·开发语言
123过去6 小时前
wifi-honey使用教程
linux·网络·测试工具
ZTLJQ6 小时前
数据的基石:Python中关系型数据库完全解析
开发语言·数据库·python
夏霞7 小时前
c# signlar 客户端传递参数给服务端配置方法
开发语言·c#
迷藏4947 小时前
**发散创新:基于 Rust的开源权限管理系统设计与实战**在现代软件架构中,**权限控制**早已不
java·开发语言·rust·开源
2301_818419017 小时前
C++中的解释器模式变体
开发语言·c++·算法
Deitymoon8 小时前
linux——孤儿进程和僵尸进程
linux
摇滚侠8 小时前
Java 项目《谷粒商城-1》架构师级Java 项目实战,对标阿里 P6-P7,全网最强,实操版本
java·开发语言
biter down8 小时前
C++11 统一列表初始化+std::initializer_list
开发语言·c++
Linux运维技术栈9 小时前
生产环境Linux应用目录迁移至LVM独立分区 标准化实战方案
linux·运维·服务器·lvm·逻辑卷