天天看點

MFC建立多線程執行個體

    平時在MFC裡使用多線程時其實是很方面的,因為微軟提供了一個API讓我們很方面的去建立線程:下面是MSDN中關于CreateThread的函數原型:

1、函數原型聲明:

 CreateThread

The CreateThread function creates a thread to execute within the virtual address space of the calling process.

To create a thread that runs in the virtual address space of another process, use the CreateRemoteThread function.

HANDLE CreateThread(

LPSECURITY_ATTRIBUTES lpThreadAttributes,

SIZE_T dwStackSize,

LPTHREAD_START_ROUTINE lpStartAddress,

LPVOID lpParameter,

DWORD dwCreationFlags,

LPDWORD lpThreadId

);

2、參數說明:

  lpThreadAttributes:指向SECURITY_ATTRIBUTES型态的結構的指針。在Windows 98中忽略該參數。在Windows NT中,它被設為NULL,表示使用預設值。

  dwStackSize,線程堆棧大小,一般=0,在任何情況下,Windows根據需要動态延長堆棧的大小。

  lpStartAddress,指向線程函數的指針,形式:@函數名,函數名稱沒有限制,但是必須以下列形式聲明:

  DWORD WINAPI ThreadProc (LPVOID pParam) ,格式不正确将無法調用成功。

  lpParameter:向線程函數傳遞的參數,是一個指向結構的指針,不需傳遞參數時,為Nil。

  dwCreationFlags :線程标志,可取值如下

  CREATE_SUSPENDED: 建立一個挂起的線程

  0 :建立後立即激活。

  lpThreadId:儲存新線程的id。

3、傳回值:

  函數成功,傳回線程句柄;函數失敗傳回false。

4、執行個體代碼:

  A、建立一個對話框工程為MFC,在MFCDlg.h添加兩個成員函數,注意一定要是靜态的,代碼如下:

/

// CMFCDlg dialog

class CMFCDlg : public CDialog

{

// Construction

public:

CMFCDlg(CWnd* pParent = NULL); // standard constructor

// 線程B1、B2函數

static DWORD WINAPI ThreadB1(LPVOID lpParam);

static DWORD WINAPI ThreadB2(LPVOID lpParam);

......

}

  B、在cpp檔案中實作函數,添加代碼如下:

  C、然後在對話框初始化時建立程序即可,代碼如下:

BOOL CMFCDlg::OnInitDialog()

CDialog::OnInitDialog();

// Set the icon for this dialog. The framework does this automatically

// when the application's main window is not a dialog

SetIcon(m_hIcon, TRUE); // Set big icon

SetIcon(m_hIcon, FALSE); // Set small icon

// TODO: Add extra initialization here

DWORD dw1,dw2;

CreateThread(NULL,0,ThreadB1,NULL,0,&dw1);

Sleep(100);

CreateThread(NULL,0,ThreadB2,NULL,0,&dw2);

return TRUE; // return TRUE unless you set the focus to a control