MatCom_C++(MultiThread)解决线程的冲突问题

MatCom_C++(MultiThread)解决线程的冲突问题

一.配置matlib.h 和 v4501v.lib文件

二.编程:

1.在XXApp类中,添加头文件#include<matlib.h>

  在XXDlg类中,添加头文件#include<matlib.h>

2. 在XXApp类的初始化实例函数中:

BOOLCMatlab_MultithreadApp::InitInstance()

{

       //在创建对话框之前,初始化MATCOM

       initM(MATCOM_VERSION);

       CMatlab_MultithreadDlgdlg;

}

 

3.在整个程序结束之前,需要调用exitM():对XXApp类,添加ExitInstance()虚函数。

int CMatlab_MultithreadApp::ExitInstance()

{

       exitM();

       return CWinApp::ExitInstance();

}

 

4.在XXDlg类中,

a.添加画图按钮的相应函数

void CMatlab_MultithreadDlg::OnBnClickedButtonDrawpicture()

{

       Mm t,y;

 

       t = linspace(0.0,1.0,400);

       y = sin(2.0*pi*4*t);//建立一个4赫兹的正弦曲线

 

       winaxes(m_hWnd);//在指定的窗口中建立坐标轴

       axesposition(130,20,300,200);//确定窗口位置和图形大小

 

       plot((CL(t),y));

}

 

b.添加刷新按钮的相应函数

添加全局变量:BOOL bExit = FALSE;为了点击停止的时候让它停止

void CMatlab_MultithreadDlg::OnBnClickedButtonRefresh()

{

       int nValue = 0;

       CString str;

       bExit = FALSE;

 

       while (!bExit)

       {

              nValue++;

              str.Format("%d",nValue);

              GetDlgItem(IDC_EDIT)->SetWindowText(str);

              Sleep(50);//每隔50毫秒,循环一次。

       }

 

c.停止按钮的响应函数。

void CMatlab_MultithreadDlg::OnBnClickedButtonStop()

{

       bExit = TRUE;

}

 

d.但是这个程序运行时会出现无响应等问题。所以,要把刷新的代码放在一个线程里完成。

void CMatlab_MultithreadDlg::OnBnClickedButtonRefresh()

{

       bExit = FALSE;

//新建一个线程,第一个参数为要调用的函数名称,第二个参数为,需要传递的参数,我们把这个窗口的指针传进去。

       AfxBeginThread(ThreadProc,(LPVOID)this);

}

 

编写ThreadProc函数。可以查看AfxBeginThread的帮助,看看它第一个参数的写法。

UINT ThreadProc(LPVOID pParam)

{

       int nValue = 0;

       CString str;

 

//创建一个指针来接受输入的参数。

CMatlab_MultithreadDlg *pDlg = (CMatlab_MultithreadDlg*)pParam;

       while (!bExit)

       {

              nValue++;

              str.Format("%d",nValue);

              //GetDlgItem(IDC_EDIT)->SetWindowText(str);//不能直接调用。

              pDlg-> GetDlgItem(IDC_EDIT)->SetWindowText(str);

              Sleep(50);//每隔50毫秒,循环一次。

       }

return 0;

}

 

5.在有的机器上会出现窗口关闭了,在任务栏仍然有这这个程序。(我的机器上没出项这种情况)所以把第三步改为

int CMatlab_MultithreadApp::ExitInstance()

{

       exitM();

Sleep(500);

       return CWinApp::ExitInstance();

}

 

posted on 2012-10-05 21:19  daxiaoyuyu  阅读(680)  评论(0)    收藏  举报

导航