jjzjj

C++ Windows 线程和互斥问题

coder 2024-06-19 原文

我对线程程序有点生疏,尤其是在 Windows 中。 我在 Matlab 中创建了一个简单的 mex 文件,用于读取多个文件,每个文件都在其自己的线程中读取。 该文件并没有做任何真正有用的事情,而是一个更复杂版本的前身,该版本将使用我放入该文件的所有功能。 这是代码:

#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);

我在 Matlab 中这样编译它:

mex readFile.cpp

然后像这样运行它:

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

问题是,当我将 nFiles 设置为小于或等于 64 时,一切都按预期工作,我得到以下输出:

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

然而,当我将 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.

我也在没有线程的情况下测试了它,它工作正常。

我看不出我做错了什么,也看不出为什么使用互斥锁的截止会如此随意,所以我假设有一些我没有考虑到的东西。 任何人都可以看到与我看到的错误相关的明显错误吗?

最佳答案

WaitForMultipleObjects 的文档中,“对象句柄的最大数量是 MAXIMUM_WAIT_OBJECTS。”,在大多数系统上为 64。

这也是(几乎)this thread 的拷贝.总结真的就是,是的,限制是 64,并且还使用 WaitForMultipleObjects 的备注部分中的信息来构建要等待的线程树。

关于C++ Windows 线程和互斥问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8130384/

有关C++ Windows 线程和互斥问题的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  3. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  4. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  5. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  6. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  7. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  8. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  9. ruby - 在 Windows 机器上使用 Ruby 进行开发是否会适得其反? - 2

    这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby​​-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub

  10. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

随机推荐