近期动态库中使用openmp,项目调用导致出错,查找许久没找到原因。项目中使用的接口也是奇怪,写了个demo程序模拟,发现有可能是因为动态库中使用的并发资源还未释放掉,动态库就被释放了,导致出错。现在将demo代码贴出,在析构函数内添加sleep函数或者在释放掉动态库之前调用sleep函数,现在贴出代码仅供参考:
主程序 :
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "windows.h"
#include <iostream>
#include "dll.h"
#include <omp.h>
using namespace std;
typedef void(*getChars)(HANDLE handl);
typedef MyClass*(*getClassAddr)();
typedef void(*deleteClass)(HANDLE handl);
void test1()
{
char *p = new char[256];
HINSTANCE m_hDec = LoadLibraryA("ConsoleApplicationdll.dll");
if (!m_hDec)
{
cout << "1 " << m_hDec<< endl;
return;
}
getClassAddr pAddr = (getClassAddr)GetProcAddress(m_hDec, "create");
if (!pAddr)
{
cout << "2" << endl;
return;
}
getChars getchars = (getChars)GetProcAddress(m_hDec, "getchars");
if (!getchars)
{
cout << "3" << endl;
return;
}
deleteClass del = (deleteClass)GetProcAddress(m_hDec, "deleteclass");
if (!del)
{
cout << "4" << endl;
return;
}
MyClass *myclass = pAddr();
getchars(myclass);
cout << p << endl;
del(myclass);
Sleep(200);//此处添加sleep函数也可以
FreeLibrary(m_hDec);}int _tmain(int argc, _TCHAR* argv[]){test1();getchar();return 0;}
dll.h
#pragma once
#include <windows.h>
#define DllExport __declspec(dllexport)
class MyClass
{
public:
MyClass();
~MyClass();
void getchars(char*p);
void unmount();
private:
void test( long, bool &);
};
#include "stdafx.h"
#include <omp.h>
#include "dll.h"
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
// Sleep(200);//此处添加sleep函数可以
}
void testt()
{
WORD bFindAFileHead = 0;
#pragma omp parallel for
for (long i = 0; i < 100000000; ++i)//只有匹配头部的时候才会同一个扇区都去匹配文件头部
{
bFindAFileHead++;
}
#pragma omp barrier
}
void MyClass::getchars(char*p)
{
bool bflag = false;
if (p == nullptr)
{
p = new char[100];
}
bool bFindAFileHead = false;
#pragma omp parallel for
for (long i = 0; i < 1000000; ++i)
{
bFindAFileHead = false;
if (!bFindAFileHead)
{
//test(i, bFindAFileHead);
}
}
// }
#pragma omp barrier
#pragma omp single
memcpy(p/**p*/, "asdfasdfasdfasdfasdfasdf", 50);
}
void MyClass::test(long i, bool &bFindAFileHead)
{
bool bflag = false;
for (long k = 0; k < 100000000; ++k)
{
if (k == 5000)
{
bflag = true;
break;
}
}
}
void MyClass::unmount()
{
delete this;
}
// ConsoleApplicationdll.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "dll.h"
#include <omp.h>
extern "C" DllExport MyClass* create()
{
return new MyClass();
}
extern "C" DllExport void getchars(HANDLE handl)
{
MyClass *pp = (MyClass*)handl;
char *p = new char[256];
pp->getchars(p);
}
extern "C" DllExport void deleteclass(HANDLE handl)
{
MyClass *pp = (MyClass*)handl;
pp->unmount();
}
demo代码
http://pan.baidu.com/s/1jISfH7S