0

How to Explicitly Allocate memory to a Thread in C++ ? Am using Windows API for Multi-threading.While running sometimes it executes correctly but sometimes it shows "Heap Corruption","Unhandled Exception".Please guide me

This is the main() where i create the threads.

int main(int argc,char *argv[])
    {
        HANDLE hthread[MAX_THREADS];
        //DWORD threadid;
        FILETIME creation,exit,kernel,user;
        SYSTEMTIME st1,st2;
        //THREADENTRY32 entry;
        char szEntrytime[255],szExittime[255];

        directories.push_front(argv[1]);
        files.clear();
        Sem = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
        if (Sem == NULL) 
        {
            printf("CreateSemaphore error: %d\n", GetLastError());
            return 1;
        }

        for(int i= 0;i<MAX_THREADS;i++)
        {
            hthread[i] = CreateThread(NULL,0,List,NULL,0,&threadid);
            //hthread[i] = HeapAlloc(GetProcessHeap(),HEAP_NO_SERIALIZE,1024*30);
             if( hthread[i] == NULL )
            {
                printf("CreateThread error: %d\n", GetLastError());
                return 1;
            }
        }

Inside Thread

while(!directories.empty())
    {
        string path = directories.front();
        string spec = path + "\\" + "*";
        WaitForSingleObject(Sem,0L);
        directories.pop_front();
        ReleaseSemaphore(Sem,1,NULL);

        HANDLE hfind = FindFirstFileA(spec.c_str(),&ffd);
        if(hfind == INVALID_HANDLE_VALUE)
            continue;
        cout<< path <<endl;;
        do
        {
            if(strcmp(ffd.cFileName,".") && strcmp(ffd.cFileName,".."))
            {
                if(ffd.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
                {
                    WaitForSingleObject(Sem,0L);
                    directories.push_front(path + "\\" + ffd.cFileName);
                    ReleaseSemaphore(Sem,1,NULL);
                }
                else
                {
                    files.push_back(path + "\\" + ffd.cFileName);
                    Files++;
                }
            }
        }while(FindNextFileA(hfind,&ffd));
Baalki
  • 61
  • 1
  • 6
  • 4
    Use `new` in the normal way. You are clearly doing it wrong, but since you declined to tell us what you are doing, nobody but you can diagnose the errors in your code. – David Heffernan Jan 22 '14 at 11:30
  • Am working on Multi-Threading to list files in a Directory.I implemented it with 4 threads.But while running it shows errors like "Heap Corruption".I surfed net and found the problem is related with memory . – Baalki Jan 22 '14 at 12:03
  • Showing the error and the code might be helpful if you need more concrete answers. – Ferenc Deak Jan 22 '14 at 12:10
  • Please show some code, and show the exact error messages and the place in your code where the debugger leads you. With the information you've given, nobody is going to be able to help you more. – Roger Rowland Jan 22 '14 at 13:04
  • I edited the post with code...Sometimes it throw the error like "Unhandled exception at 0x60f1ad54 (msvcp100d.dll) in Directory Listing.exe: 0xC0000005: Access violation writing location 0xdddddddd." and sometimes like "This may be due to a corruption of the heap, which indicates a bug in Directory Listing.exe or any of the DLLs it has loaded." I dunno what is the exact problem.Debugger lead me to different header like xutility.h,xmemory.h,free.c – Baalki Jan 22 '14 at 13:25
  • I don't see the point of using `WaitForSingleObject` with a `0` timeout. Use `INFINITE` instead. Anyway, maybe that won't fix you problems as you seem to not always protect your shared variables (`directories` and `files`). You should describe what you are trying to do, we can't guess. – manuell Jan 22 '14 at 14:03
  • @manuell i posted already ... directories is a deque variable which stores the folders and files is a vector variable which holds files.Each time when i insert a folder in directory a thread will process it insert its subfolders and stores the files in vector. – Baalki Jan 22 '14 at 14:15
  • Update your question, then. `directories` and `files` declaration are NOT here. and what does mean "when i insert a folder in directory"? You create 4 threads. Are they all looping on `!directories.empty()`? – manuell Jan 22 '14 at 14:22
  • 1
    "[If a single object is being written to by one thread, then all reads and writes to that object on the same or other threads must be protected](http://msdn.microsoft.com/en-us/library/c9ceah3b.aspx)." You are writing to `directories` but are not protecting `directories.empty()` or `directories.front()`. Also, your protection is inadequate. And `files` is totally unprotected. – Raymond Chen Jan 22 '14 at 14:32
  • @manuell yes all the four threads will work until directories become empty..@Raymond do i have to include the loop inside the semaphore in order for protected access – Baalki Jan 22 '14 at 14:59
  • If there is only one directory at the start, 3 threads may exit immediately, even if sub-directories are to be processed. Why are you using threads in the first place? – manuell Jan 22 '14 at 15:32

2 Answers2

0

Use critical section for access shared resource:
EnterCriticalSection(&my_section);
//perform data manipulation per-thread
LeaveCriticalSection(&my_section);

Do not forget to initialize the critical section before using.
See this question to get help Problems using EnterCriticalSection

Community
  • 1
  • 1
lsalamon
  • 7,998
  • 6
  • 50
  • 63
0

Use following logic for your threads (pseudo-code):

while ( true ) {

    lock()
    if ( empty ) {
       unlock;
       sleep;
       continue;
    } else {
       get_one_dir;
       remove_that_dir_from_list;
       unlock;
    }
    process_the_dir;
    continue;
}

For lock, use a Critical Section, and lock/unlock again when you want to push a new dir in the list.

Use same lock/unlock logic when reading/writing the files vector.

manuell
  • 7,528
  • 5
  • 31
  • 58
  • thanks for the logic u gave....But it shows "Unhandled exception at 0x76f68e19 in Directory Listing.exe: 0xC0000005: Access violation writing location 0x00000014." This error incurred when reaches lock() statement inside while. – Baalki Jan 22 '14 at 19:02
  • please can u provide some more optimisation to be done in the logic – Baalki Jan 23 '14 at 07:55