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

输出:

相关推荐
CUMT_DJ1 小时前
matlab计算算法的运行时间
开发语言·算法·matlab
Overboom4 小时前
[C++] --- 常用设计模式
开发语言·c++·设计模式
Univin4 小时前
C++(10.4)
开发语言·数据结构·c++
KyollBM4 小时前
每日羊题 (质数筛 + 数学 | 构造 + 位运算)
开发语言·c++·算法
青草地溪水旁4 小时前
linux信号(14)——SIGALRM:从“手机闹钟”看SIGALRM:进程的非阻塞定时神器
linux·信号机制
心灵宝贝5 小时前
libopenssl-1_0_0-devel-1.0.2p RPM 包安装教程(openSUSE/SLES x86_64)
linux·服务器·数据库
Paul_09206 小时前
golang面经——map模块和sync.Map模块
开发语言
BullSmall6 小时前
linux zgrep命令介绍
linux·运维
Univin6 小时前
C++(10.5)
开发语言·c++·算法
haogexiaole6 小时前
Java高并发常见架构、处理方式、api调优
java·开发语言·架构