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

输出:

相关推荐
沐知全栈开发5 分钟前
NumPy 统计函数
开发语言
风语者日志15 分钟前
[LitCTF 2023]Vim yyds
linux·编辑器·vim
Thexhy34 分钟前
在centos 7上配置FIP服务器的详细教程!!!
linux·运维·centos
chao18984438 分钟前
C 文件操作全解速览
服务器·c语言·c#
青光键主43 分钟前
C语言内功强化之const修饰指针
c语言·开发语言
骷大人1 小时前
php安装skywalking_agent
开发语言·php·skywalking
恋恋西风2 小时前
Qt 打开文件列表选择文件,实现拖拽方式打开文件,拖拽加载
开发语言·qt
Java 码农2 小时前
Linux shell sed 命令基础
linux·运维·服务器
yong15858553432 小时前
1. Linux C++ muduo 库学习——库的编译安装
linux·c++·学习
fyakm2 小时前
Linux网络接口配置:静态IP与动态IP设置(附代码示例)
linux·运维·tcp/ip