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
原创粉丝点击