通过线程写文件的例子

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

#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;
}
改掉路径名,重新编译即可运行。

你可能感兴趣的:(C++,线程,linux)