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

输出:

相关推荐
虾..19 分钟前
Linux HTTP服务器
linux·服务器·http
m0_7166670720 分钟前
实时数据压缩库
开发语言·c++·算法
dapeng287027 分钟前
多协议网络库设计
开发语言·c++·算法
浅浅的小草29 分钟前
APM使用LUA脚本发送实现遥控器PWM信号输出CAN协议信号
开发语言·apm
星空露珠35 分钟前
又双叒叕统计被炸死的lua脚本
开发语言·数据结构·算法·游戏·lua
LONGZETECH44 分钟前
新能源汽车维护仿真软件技术架构解析+ 教学落地实操
大数据·c语言·人工智能·架构·汽车·汽车仿真教学软件·汽车教学软件
sinat_255487811 小时前
transient 修饰符·学习笔记
java·开发语言·spring
阿猿收手吧!1 小时前
【C++】建造者与代理模式实战解析
开发语言·c++·代理模式
WYH2871 小时前
FreeRTOS工程项目实践
c语言·单片机·嵌入式硬件·学习
2501_945424801 小时前
C++跨平台开发实战
开发语言·c++·算法