通过线程写文件的例子

来源:互联网 发布:rds数据库 编辑:程序博客网 时间:2024/06/06 22:19

两个线程,分别写两个文件。

#include<iostream>#include<fstream>#include<pthread.h>#include <stdlib.h>#include <string>using namespace std;pthread_t tid1;pthread_t tid2;typedef struct a_param{    ofstream fd;    string filename;    string data;}PARAM;void* writefile(void *arg){    PARAM *tmp = (PARAM *)arg;    tmp->fd.open(tmp->filename.c_str());    if(!tmp->fd)    {        cout<<"unable to open :"<<tmp->filename<<endl;        exit(-1);    }    tmp->fd<<tmp->data;    tmp->fd.close();    pthread_exit(0);}int main(){    string file1="/home/app/ShallPractice/file1.txt";    string file2="/home/app/ShallPractice/file2.txt";PARAM redata1;    redata1.filename =file1;    redata1.data ="I am the file1 \n";    PARAM redata2;    redata2.filename =file2;    redata2.data ="I am the file2 \n";int t = pthread_create(&tid1,NULL,writefile,&redata1);if(t!=0)    {        cout<<"Thread1 create error!"<<endl;        exit(-1);    }t = pthread_create(&tid2,NULL,writefile,&redata2);    if(t!=0)    {        cout<<"Thread2 create error!"<<endl;        exit(-1);    }    pthread_join(tid1, NULL);      pthread_join(tid2, NULL);      return 0;}
改掉路径名,重新编译即可运行。

0 0
原创粉丝点击