簡體   English   中英

使用Win32 API在C ++中使用多線程創建多個文件

[英]Create multiple files using multi threading in C++ using Win32 API

我正在嘗試在筆式驅動器中創建文件。 如果筆驅動器不存在,則線程應掛起。 插入后應繼續。 這是我嘗試的代碼,但無法正常工作。 誰能幫我?

 #include "stdafx.h"
    #include <Windows.h>
    #include <Strsafe.h>
    #include <WinBase.h>


        LPCTSTR Disk=L"E:\";

        LPTSTR drive_Name=L"E:\\demo";

        CRITICAL_SECTION section;


         #define BUFFER_SIZE 1024
         #define count 10

        HANDLE Write_Handle[10],Open_Handle[10],read_Handle[10] ;

        DWORD WINAPI check_Thread(LPVOID lpParameter)

        {

        int *nThreadNo = (int*)lpParameter;

        while(1)

        {

                if(GetDiskFreeSpaceExW(Disk,NULL,NULL,NULL))

                {

                    ResumeThread(Write_Handle[*nThreadNo]);
                    ResumeThread(read_Handle[*nThreadNo]);
                }
                else
                {
                    SuspendThread(Write_Handle[*nThreadNo]);
                    SuspendThread(read_Handle[*nThreadNo]);
                }
            }

        }


        DWORD  WINAPI Write_Thread(LPVOID lpParameter)
        {
            DWORD g_tid = GetCurrentThreadId();
            _tprintf(_T(" write thread id %d\n"),g_tid);
            LPCWSTR  filename=(LPCWSTR)lpParameter;
            HANDLE ofile;
            EnterCriticalSection(&section);
            ofile=CreateFileW(filename,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_ALWAYS,NULL, NULL);
            int d;
                d=GetLastError();
                if(ERROR_SUCCESS!=GetLastError())
                {
                    _tprintf(_T("error values in open thread %d \n"),GetLastError());
                    _tprintf(_T("filename %s \n"),filename);
                }

            const int filesizeinKB = 1024;
            BOOL bError;
            DWORD dwBytesWritten=0;
             WCHAR ReadBuffer[BUFFER_SIZE] = {0};
            int i;


            for(i = 0; i <= BUFFER_SIZE; i++)
            {
                ReadBuffer[i] = (char)(i%26 + 'a');
            }
            for (i = 0; i <= filesizeinKB; i++)
            {
                SetLastError(0);
                bError= WriteFile(ofile, ReadBuffer-1, BUFFER_SIZE,&dwBytesWritten, NULL);
                bError=GetLastError();

                if (ERROR_SUCCESS!=GetLastError())
                {   _tprintf(_T("error value in write %d\n"),GetLastError());
                    _tprintf(_T(" Write Error...\n"));
                        return 1;
                }

            }
            SetLastError(0);
            CloseHandle(ofile);
            _tprintf(_T("write close error values %d\n"),GetLastError());
            LeaveCriticalSection(&section);
            return 1;
        }


        DWORD WINAPI Read_Thread(LPVOID lpParameter)
        {
            HANDLE ofile;
            DWORD g_tid = GetCurrentThreadId();
            _tprintf(_T(" write thread id %d\n"),g_tid);
            LPCWSTR  filename=(LPCWSTR)lpParameter;
            EnterCriticalSection(&section);
            ofile=CreateFileW(filename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_ALWAYS,NULL, NULL);
            int d;
                d=GetLastError();
                if(ERROR_SUCCESS!=GetLastError())
                {
                    _tprintf(_T("error values in open thread %d \n"),GetLastError());
                    _tprintf(_T("filename %s \n"),filename);
                }

            DWORD dwBytesRead=0;
             WCHAR ReadBuffer[BUFFER_SIZE] = {0};
            _tprintf(_T(" read thread \n"));
            SetLastError(0);
            int err;

            ReadFile(ofile, ReadBuffer, (BUFFER_SIZE-1), &dwBytesRead, NULL);

                err=GetLastError();
                _tprintf(_T("read error values %d \n"),GetLastError());
                if(ERROR_SUCCESS!=GetLastError())
                {
                    _tprintf(L"reading failed \n");
                    return 0;
                }
                SetLastError(0);
                CloseHandle(ofile);
                err=GetLastError();
                _tprintf(_T("close error values %d\n"),GetLastError());
                LeaveCriticalSection(&section);
                return 1;
        }


        int _tmain(int argc, _TCHAR* argv[])
        {

            unsigned int myCounter = 0;
            DWORD WritethreadID,OpenThreadID,ReadthreadID;
            HANDLE check_Handle;
             DWORD exThread;
            TCHAR filename[100];
            HANDLE hfile;
            INT bsize=100;
            int i=0;

            InitializeCriticalSection (&section);
            CreateDirectory(drive_Name,NULL);

            for(i=0;i<5;i++)
            {
                SetLastError(0);
                StringCchPrintf(filename,bsize, TEXT("%s\\file_%d.txt"),drive_Name,i );
                hfile=CreateFileW(filename,GENERIC_WRITE|GENERIC_READ,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

                if (hfile == INVALID_HANDLE_VALUE) 
                { 
                    _tprintf(_T("invalid handle \n" ));

                }
                _tprintf(_T("file created %s\n"),filename);
                CloseHandle(hfile);

                Write_Handle[i] =CreateThread(0, 0, Write_Thread, filename, CREATE_SUSPENDED, &WritethreadID);
                SetThreadPriority(Write_Handle[i],2);
                _tprintf(_T("write thread id is %d\n"),WritethreadID);
                read_Handle[i]=CreateThread(0, 0, Read_Thread, filename, CREATE_SUSPENDED, &ReadthreadID);
                SetThreadPriority(read_Handle[i],1);
                _tprintf(_T("read thread id is %d\n "),ReadthreadID);
                check_Handle =CreateThread(0, 0, check_Thread,(void*)&i ,0,&OpenThreadID);
            }   
            for (i=0; i<count; ++i)
            {
                WaitForSingleObject(Write_Handle[i],INFINITE); 
                if ( !GetExitCodeThread(Write_Handle, &exThread) ) 
                {  
                    _tprintf(_T("close thread %08X\n"),GetLastError()); 

                }
                SetLastError(0);
                CloseHandle(Write_Handle[i]);
                _tprintf(_T("close thread %08X\n"),GetLastError()); 
                WaitForSingleObject(read_Handle[i],INFINITE); 
                if ( !GetExitCodeThread(read_Handle, &exThread) ) 
                {  
                    _tprintf(_T("GetExitCodeThread %08X\n"),GetLastError()); 
                } 
                SetLastError(0);
                CloseHandle(read_Handle[i]);
                _tprintf(_T("GetExitCodeThread %08X\n"),GetLastError()); 

                CloseHandle(check_Thread);

            }

            DeleteCriticalSection(&section);
            return 1;

        }

如果卸下USB驅動器時有打開的文件句柄,則這些文件句柄將變為無效。 重新插入USB驅動器不會以恢復線程后可以繼續的方式重新構造這些句柄。

您將需要:

  • 檢測何時刪除設備,並關閉那些現在已經斷開的手柄
  • 插入設備后,再次打開文件,然后繼續執行操作

您的錯誤處理程序將在不調用LeaveCriticalSection的情況下返回,從而使CS被鎖定並無限期地阻塞其他線程。 EnterCriticalSection文檔中:

  • 如果線程在擁有臨界區的所有權時終止,則臨界區的狀態未定義。

這些情況也會使文件句柄保持打開狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM