linux C++多线程操作文件&输出加锁
下述demo将指定目录下文件存入vector,然后一分为二交给两个线程(threadTask1,threadTask2)去分别处理,对输出函数printDirent加锁防止紊乱。
#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; }