linux c++ 多线程代码 对文件的读写
来源:互联网 发布:js解除绑定click事件 编辑:程序博客网 时间:2024/04/29 00:03
#include <iostream>
#include <fstream>#include <pthread.h>
using namespace std;
pthread_mutex_t file_mutex;
void* product(void * arg){
for(int i = 0; i < 10 ; i++){
pthread_mutex_lock(&file_mutex);
ofstream file;
file.open("file.txt", ios::app);
if(file.good()){
file << i << std::endl;
file.close();
}
pthread_mutex_unlock(&file_mutex);
}
}
void* consume(void * arg){
for(int i=0 ; i< 4; i++ ){
pthread_mutex_lock(&file_mutex);
char buf[1000] ;
ifstream file;
file.open("file.txt");
while(file.good()){
file.getline(buf, 1000);
std::cout << "buf:" << buf << std::endl;
}
file.close();
pthread_mutex_unlock(&file_mutex);
}
}
int main(int argc, char* argv[]){
pthread_t producer_id;
pthread_t consumer_id;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&producer_id, &attr, product, NULL);
pthread_create(&consumer_id, &attr, consume, NULL);
pthread_join(producer_id, NULL);
pthread_join(consumer_id, NULL);
}
文件名:test.cpp
执行 命令:g++ test.cpp -lpthread
1 0
- linux c++ 多线程代码 对文件的读写
- C对文件的读写
- java多线程读写同一个文件的代码
- C语言多线程的应用--局域网中多台计算机对同一文件读写
- C/C++对文件的读写
- linux下对文件的读写操作
- Linux C 读写文件
- 对文件的读写;
- Linux与C语言的文件读写
- Java代码实现对properties文件有序的读写
- Java代码实现对properties文件有序的读写
- C语言中对文件的读写函数
- C#:基于LINQ实现对ini文件的读写
- 关于c语言对文件的打开读写
- C\C++对大文件的快速读写
- C\C++对大文件的快速读写
- C语言对xml文件的读写操作
- C语言对文件的交替读写问题
- 互联网架构,如何进行容量设计?
- zoj 3327 Friend Number 枚举 分类讨论 模拟
- 表格隔行变色怎么写?
- 编译git遇到的perl-ExtUtils-MakeMaker错误
- Android N使用Ubuntu 14.04系统搭建编译环境
- linux c++ 多线程代码 对文件的读写
- notepad中安装Emmet插件
- ViewPager+Fragment取消预加载(实现只加载一页的效果)
- 自定义可圆形移动的view
- C++中 vector可使用的函数和使用方式
- ORACLE数据类型之FLOAT
- 线程数究竟设多少合理
- Android 实现一次性闹钟和周期性闹钟
- linux驱动-内核中的数据类型