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

输出:

相关推荐
kill bert42 分钟前
Java八股文背诵 第四天JVM
java·开发语言·jvm
低头专研2 小时前
Markdown标题序号处理工具——用 C 语言实现
c语言·开发语言·typora·markdown文件标题编号·md文件标题序号
Starry_hello world2 小时前
Linux 的准备工作
linux·笔记·有问必答
_考不上研究生不改名3 小时前
【完美解决】VSCode连接HPC节点,已配置密钥却还是提示需要输入密码
linux·服务器·vscode·远程连接·hpc·超算集群
_长银4 小时前
Vim搜索和替换
linux·编辑器·vim
刚入门的大一新生4 小时前
C++初阶-C++入门基础
开发语言·c++
你是理想4 小时前
wait 和notify ,notifyAll,sleep
java·开发语言·jvm
forestsea4 小时前
Python进阶编程总结
开发语言·python·notepad++
q567315234 小时前
使用Java的HttpClient实现文件下载器
java·开发语言·爬虫·scrapy
weixin_428498495 小时前
Visual Studio 中使用 Clang 作为 C/C++ 编译器时,设置优化选项方法
c语言·c++·visual studio