Salve a tutti.
Devo realizzare un programma multithread che cerca una stringa nei file contenuti in un dato path (e nelle sottodirectory eventualmente contenute). I thread devono essere 20.
Ho scritto questo codice:
Mi escono risultati non sempre uguali e spesso (ma non sempre) mi esce questo errore:codice:#include "stdafx.h" #include <windows.h> #include <fstream> #include <iostream> #include <string> #include <process.h> using namespace std; void EsploraDirectory(string dir); unsigned int WINAPI LeggiFile(LPVOID lpParam); string str; string::iterator it; HANDLE hThreads[19]; unsigned threadID; int count = 0; class win32Critical_Section { // simple class that wraps a Win32 Critical_Section private: CRITICAL_SECTION cs; public: void lock(); void unlock(); win32Critical_Section(); ~win32Critical_Section(); }; win32Critical_Section::win32Critical_Section() { InitializeCriticalSection(&cs); } win32Critical_Section::~win32Critical_Section() { DeleteCriticalSection(&cs); } void win32Critical_Section::lock() { EnterCriticalSection(&cs); } void win32Critical_Section::unlock() { LeaveCriticalSection(&cs); } class Guard { win32Critical_Section& cs; public: Guard(win32Critical_Section& cs): cs(cs) { cs.lock(); } ~Guard() { cs.unlock(); } }; win32Critical_Section gCS; int _tmain(int argc, char *argv[]) { if(argc != 3) { cerr << "Usage: " << argv[0] << " <cartella origine> <stringa da cercare>" << endl; return -1; } str = argv[2]; EsploraDirectory(argv[1]); return 0; } void EsploraDirectory(string dir) { WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; DWORD dwError=0; string pattern, path; pattern = dir + "\\*"; hFind = FindFirstFile(pattern.c_str(), &ffd); if (INVALID_HANDLE_VALUE == hFind) { cerr << "FindFirstFile failed (" << GetLastError() << ")" << endl; return; } do { path.erase(); path = dir + "\\" + ffd.cFileName; if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(lstrcmp(ffd.cFileName, TEXT(".")) && lstrcmp(ffd.cFileName, TEXT(".."))) EsploraDirectory(path); } else { string *stringaPtr = new string(path); hThreads[count++] = (HANDLE)_beginthreadex( NULL, 0, &LeggiFile, reinterpret_cast<void*>(stringaPtr), 0, &threadID ); } } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); WaitForMultipleObjects(count-1,hThreads,TRUE,INFINITE); } unsigned int WINAPI LeggiFile(LPVOID lpParam) { ifstream fin; string riga; char c; it = str.begin(); string *nomefile = reinterpret_cast<string*>(lpParam); try { Guard l(gCS); fin.open(nomefile->c_str()); while (fin.good()) { c = fin.get(); if (c == *it) it++; else it = str.begin(); if (it == str.end()) { cout << "Stringa " << str << " trovata nel file " << *nomefile << endl; break; } } fin.close(); } catch (...) { } return 0; }
Che problema può essere?
Grazie anticipatamente.


Rispondi quotando