Linux C++ multi-threaded operation file & output locking

The following demo stores the files in the specified directory into the vector, and then divides them into two threads (threadTask1, threadTask2) to process them separately, and locks the output function printDirent to prevent confusion.

#include <iostream>
#include <string>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <list>
#include <numeric>
#include <algorithm>
#include <vector>

static pthread_mutex_t testlock;
using namespace std; 
void *threadTask1(void *ptr);
void *threadTask2(void *ptr);
typedef vector<dirent> VECTORDIRENT;
VECTORDIRENT listDirent;
VECTORDIRENT::iterator iter; 
void printStr(string buff);
void printDirent(struct dirent ptrTest);

void *threadTask1(void *ptr)
{
	int vectorI=0;
	int vectorLen = listDirent.size()/2;
	int count=0;
        for(;vectorI<vectorLen;vectorI++)
        {
    	printDirent(listDirent[vectorI]);
    	count++;
	}  
}

void *threadTask2(void *ptr)
{
	int vectorI=listDirent.size()/2;
	int vectorLen = listDirent.size();
	int count=0;
        for(;vectorI<vectorLen;vectorI++)
        {
    	printDirent(listDirent[vectorI]);
    	count++;
	}
}


void printDirent(struct dirent ptrTest){
	pthread_mutex_lock(&testlock);
	cout<<ptrTest.d_name<<endl;
	pthread_mutex_unlock(&testlock);
	
}

int main(void)
{
    DIR    *dirTest;
    struct    dirent    *ptrTest;
    string testFolderPathName = "/home/undoner/";
    dirTest = opendir(testFolderPathName.data()); ///open the dir
    int fileCount = 0;
    while((ptrTest = readdir(dirTest)) != NULL) ///read the list of this dir
    {   
		if(ptrTest->d_type==8){
			listDirent.push_back(*ptrTest);
		}
    }
    cout<<listDirent.size()<< endl; 
    cout<<"listDirent.begin()--- listDirent.end():"<<endl; 
    for (iter = listDirent.begin(); iter != listDirent.end(); ++iter) {
    	cout << iter->d_name << " "; 
    }
    pthread_t thread1,thread2;
	int ret1,ret2;
	ret1=pthread_create(&thread1,NULL,threadTask1,NULL);
	ret2=pthread_create(&thread2,NULL,threadTask2,NULL);
	//ret3=pthread_create(&thread3,NULL,thread,NULL);
	if(ret1!=0){
	printf ("Create pthread error!\n");
	exit (1);
	}
	if(ret2!=0){
	printf ("Create pthread error!\n");
	exit (1);
	}
	pthread_join(thread1,NULL);
	pthread_join(thread2,NULL);	
	return 0;
}


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324125166&siteId=291194637