简体   繁体   English

C ++ windows threading和mutex问题

[英]C++ windows threading and mutex issue

I am a bit rusty with threaded programs especially in windows. 我有点生锈的线程程序,尤其是在Windows中。 I have created a simple mex file in Matlab that is meant to read a number of files with each file being read in its own thread. 我在Matlab中创建了一个简单的mex文件,用于读取大量文件,每个文件都在自己的线程中读取。 The file doesnt do anything really useful but is a precursor to a more complicated version that will use all of the functionality ive put into this file. 该文件没有做任何真正有用的事情,但它是一个更复杂版本的前身,它将使用我放入此文件的所有功能。 Here is the code: 这是代码:

#include <windows.h>
#include "mex.h"
#include <fstream>

typedef unsigned char uchar;
typedef unsigned int uint;

using namespace std;

int N;
int nThreads;
const int BLOCKSIZE = 1024;
char * buffer;
char * out;
HANDLE    hIOMutex;

DWORD WINAPI runThread(LPVOID argPos) {
    int pos = *(reinterpret_cast<int*>(argPos));

    DWORD dwWaitResult = WaitForSingleObject( hIOMutex, INFINITE );

    if (dwWaitResult == WAIT_OBJECT_0){
        char buf[20];
        sprintf(buf, "test%i.dat", pos);
        ifstream ifs(buf, ios::binary);

        if (!ifs.fail()) {
            mexPrintf("Running thread:%i\n", pos);
            for (int i=0; i<N/BLOCKSIZE;i++) {
                if (ifs.eof()){ 
                    mexPrintf("File %s exited at i=%i\n", buf, (i-1)*BLOCKSIZE);
                    break;
                }
                ifs.read(&buffer[pos*BLOCKSIZE], BLOCKSIZE);
            }
        }
        else {
            mexPrintf("Could not open file %s\n", buf);
        }

        ifs.close();
        ReleaseMutex( hIOMutex);
    }
    else
        mexPrintf("The Mutex failed in thread:%i \n", pos);


    return TRUE;
}

// 0 - N is data size
// 1 - nThreads is number of threads
// 2 - this is the output array

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) {
    N = mxGetScalar(prhs[0]);
    nThreads = mxGetScalar(prhs[1]);
    out = (char*)mxGetData(prhs[2]);
    buffer = (char*)malloc(BLOCKSIZE*nThreads);
    hIOMutex= CreateMutex(NULL, FALSE, NULL);

    HANDLE *hArr = (HANDLE*)malloc(sizeof(HANDLE)*nThreads);
    int *tInd = (int*)malloc(sizeof(int)*nThreads);

    for (int i=0;i<nThreads;i++){
        tInd[i]=i;
        hArr[i] = CreateThread( NULL, 0, runThread, &tInd[i], 0, NULL);
        if (!hArr[i]) {
            mexPrintf("Failed to start thread:%i\n", i);
            break;
        }
    }

    WaitForMultipleObjects( nThreads, hArr, TRUE, INFINITE);

    for (int i=0;i<nThreads;i++)
        CloseHandle(hArr[i]);

    CloseHandle(hIOMutex);
    mexEvalString("drawnow");
    mexPrintf("Finished all threads.\n");

    free(hArr);
    free(tInd);
    free(buffer);

I compile it like this in Matlab: 我在Matlab中这样编译它:

mex readFile.cpp

And then run it like this: 然后像这样运行:

out = zeros(1024*1024,1,'uint8'); 
readFile(1024*1024,nFiles,out);

The problem is that when I set nFiles to be less than or equal to 64 everything works as expected and I get the following output: 问题是,当我将nFiles设置为小于或等于64时,一切都按预期工作,我得到以下输出:

Running thread:0
.
.
.
Running thread:62
Running thread:63
Finished all threads.

However when I set nFiles to 65 or larger I get: 但是,当我将nFiles设置为65或更大时,我得到:

Running thread:0
Running thread:1
Running thread:2
Running thread:3
The Mutex failed in thread:59 
The Mutex failed in thread:60 
The Mutex failed in thread:61 
.
.
.
(up to nFiles-1)
Finished all threads.

I have also tested it without threading and it works fine. 我也没有穿线测试它,它工作正常。

I cannot see what Im doing wrong or why the cutoff to using the mutex would be so arbitrary so I am assuming there is something I am not taking into account. 我无法看到我做错了什么或为什么使用互斥锁的截止是如此随意,所以我假设有一些我没有考虑到的东西。 Can anyone see where I have a blatant mistake relating to the error Im seeing? 任何人都可以看到我有一个与我看到的错误有关的明显错误?

In the documentation for WaitForMultipleObjects , "The maximum number of object handles is MAXIMUM_WAIT_OBJECTS.", which is 64 on most systems. WaitForMultipleObjects的文档中,“最大对象句柄数为MAXIMUM_WAIT_OBJECTS。”,在大多数系统上为64。

This is also (almost) a duplicate of this thread . 这也是(几乎) 该线程的副本。 The summary is really just that yes, the limit is 64, and also to use the information in the remarks section of WaitForMultipleObjects to build up a tree of threads to wait on. 总结实际上就是,限制为64,并且还可以使用WaitForMultipleObjects的备注部分中的信息来建立线程树以等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM