1、使用CreateThread()、ExitThread(0)等系统调用创建和撤销线程
- #include "stdafx.h"
- #include "线程控制.h"
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static char THIS_FILE[] = __FILE__;
- #endif
- /
- // The one and only application object
- CWinApp theApp;
- using namespace std;
- void T1();
- static HANDLE hHandle1 = NULL;
- DWORD dw1;
- int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
- {
- int nRetCode = 0;
- hHandle1 = CreateThread((LPSECURITY_ATTRIBUTES) NULL,
- 0,
- (LPTHREAD_START_ROUTINE) T1,
- (LPVOID) NULL,
- 0,
- &dw1);
- printf("32222\n");
- printf("32222\n");
- printf("32222\n");
- Sleep(1000);
- CloseHandle(hHandle1);
- ExitThread(0);
- return nRetCode;
- }
- void T1(){
- printf("23333\n");
- printf("23333\n");
- printf("23333\n");
- }
2、向线程所在函数传递一个参数
- #include "stdafx.h"
- #include "cs.h"
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static char THIS_FILE[] = __FILE__;
- #endif
- /
- // The one and only application object
- CWinApp theApp;
- using namespace std;
- void T1(int *x);
- static HANDLE hHandle1 = NULL;
- DWORD dw1;
- int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
- {
- int nRetCode = 0;
- int *x ;
- x = (int *)malloc(sizeof(int));
- scanf("%d",x);
- hHandle1 = CreateThread((LPSECURITY_ATTRIBUTES) NULL,
- 0,
- (LPTHREAD_START_ROUTINE) T1,
- (LPVOID)x,
- 0,
- &dw1);
- printf("main:%d\n",*x);
- Sleep(1000);
- CloseHandle(hHandle1);
- ExitThread(0);
- return nRetCode;
- }
- void T1(int *x){
- printf("T1:%d",*x);
- }
3、
向线程所在函数传递多个参数
- #include "stdafx.h"
- #include "csf.h"
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static char THIS_FILE[] = __FILE__;
- #endif
- /
- // The one and only application object
- CWinApp theApp;
- using namespace std;
- typedef struct{
- int x;
- int y;
- }czm;
- void T1(czm *p);
- static HANDLE hHandle1 = NULL;
- DWORD dw;
- int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
- {
- int nRetCode = 0;
- czm *p;
- p = (czm*) malloc (sizeof(czm));
- p->x = 2;
- p->y = 3;
- hHandle1 = CreateThread((LPSECURITY_ATTRIBUTES) NULL,
- 0,
- (LPTHREAD_START_ROUTINE) T1,
- (LPVOID) p,
- 0,
- &dw);
- printf("main:%d+%d=%d\n",p->x,p->y,(p->x+p->y));
- Sleep(1000);
- CloseHandle(hHandle1);
- ExitThread(0);
- return nRetCode;
- }
- void T1(czm *p){
- printf("T1:%d*%d=%d\n",p->x,p->y,(p->x*p->y));
- }