(1) 线程的创建:(主要以下2种)

CWinThread* AfxBeginThread(AFX_THREADPROC pfnThreadProc,
  LPVOID lParam,
  int nPriority =
THREAD_PRIORITY_NORMAL,
  UINT nStackSize
= 0,
  DWORD
dwCreateFlags = 0,
  LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL
  );

HANDLE
CreateThread(
  LPSECURITY_ATTRIBUTES
lpThreadAttributes, // SD
  SIZE_T
dwStackSize, // initial stack size
  LPTHREAD_START_ROUTINE
lpStartAddress, // thread function
  LPVOID
lpParameter, // thread argument
  DWORD
dwCreationFlags, // creation option
  LPDWORD
lpThreadId // thread identifier
  );

DWORD WINAPI
myroutine(LPVOID param)

{

printf("%d,hello from
subroutine!\n",*((int*)param));

return NULL;

}

int _tmain(int
argc, _TCHAR* argv[])

{

printf("hello from main!\n");

int iSub = 11;

DWORD dId;

HANDLE hThread =
CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)myroutine,(LPVOID)&iSub,0,&dId);

return 0;

}

(2) 结束线程:

BOOL CloseHandle(HANDLE hObject);

BOOLTerminateThread( HANDLEhThread,DWORDdwExitCode);

VOID
ExitThread(DWORD dwExitCode);

结束线程最好使用线程函数返回,TerminateThread和ExitThread这2种方式都不推荐使用,也尽量不用。

( 3 ) 线程的暂停/重启:

DWORD
SuspendThread( HANDLE hThread );

DWORD
ResumeThread( HANDLE hThread );

( 4 ) 线程优先级:

BOOL SetThreadPriority( HANDLE hThread,
int
nPriority ); 从主线程继承基础上设置优先级。

( 5 ) 公共资源的并发访问与同步:

临界区:

Critical_Section cs;

void main()

{

       InitializeCriticalSection(&cs);

DeleteCriticalSection(&cs);

}

DWORD WINAPI mythread(LPVOID param)

{

EnterCriticalSection(&cs);       ¬

…//操作。。。

LeaveCriticalSection(&cs);

}

锁机制:

CCriticalSection cs;

void main()

{

}

DWORD WINAPI mythread(LPVOID param)

{

cs.Lock();

cs.Unlock();

}

互斥量:

HANDLE hMutex;

void main()

{

hMutex =
CreateMutex(NULL,FALSE,”myownmutex”);

}

DWORD WINAPI mythread(LPVOID param)

{

WaitForSingleObject(hMutex,INFINITE);    ¬

ReleaseMutex(hMutex);

}

信号量:

HANDLE hSema;

void main()

{

hSema =
CreateSemaphore(NULL,nInit,nMax,”myownsemaphore”);

}

DWORD WINAPI mythread(LPVOID param)

{

WaitForSingleObject(hSema,5000L);   ¬

ReleaseSemaphore(hSema,1,NULL);

}

事件:

HANDLE hEvent;

void main()

{

hEvent =
CreateEvent(NULL,FALSE,TRUE,”myownevent”);

WaitForSingleObject(hEvent,INFINITE);     ¬

}

DWORD WINAPI mythread(LPVOID param)

{

…//操作。。。

SetEvent(hEvent);

}

05-01 03:17