线程

来源:互联网 发布:安卓数据库sqlite 编辑:程序博客网 时间:2024/05/27 20:30

1:CreateThread创建一个线程MyThread,nParameter为MyThread的唯一参数,dwThreadID线程ID。

2:CeGetThreadPriority和CeGetThreadPriority用于获取和设置线程的优先级。

3:CeGetThreadQuantum和CeGetThreadQuantum用于获取和设置线程的是时间片,如果时间片设置为0,则该线程不会被同等优先级的线程抢占。

4:SuspendThread和ResumeThread分别用于挂起线程和恢复线程运行。

5:当不需要用到线程句柄是应该关闭该句柄,防止内存泄漏。

 

// MyThread.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

#include <windows.h>

#include <commctrl.h>

 

 

DWORD MyThread(PVOID pArg)

{

     INT32 nParam = (INT32)pArg;

 

     printf("nParam:%d/n",nParam);   

 

     while(1) {

         printf("@");

         Sleep(50);

     }

 

     return 0x16;

}

 

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

{

     HANDLE hThread1;

     DWORD dwThreadID = 0;

     INT32 nParameter = 10;

 

     hThread1 = CreateThread(NULL, 0, MyThread,(PVOID)nParameter, 0, &dwThreadID);

     if(hThread1)  {

         //Priority Get and Set

         printf("old Priority:%d/n",CeGetThreadPriority(hThread1));

         CeSetThreadPriority(hThread1,0);

         printf("new Priority:%d/n",CeGetThreadPriority(hThread1));

        

         //Quantum Get and Set

         printf("old Quantum:%d/n",CeGetThreadQuantum(hThread1));

         CeSetThreadQuantum(hThread1,200);   

         printf("new Quantum:%d/n",CeGetThreadQuantum(hThread1));

 

     }    else {

         printf("CreateThread MyThread error/r/n");

         return -1;

     }   

 

     while(1) {

         Sleep(500);

         SuspendThread(hThread1);

         Sleep(3000);

         ResumeThread(hThread1);

     }

    

     CloseHandle(hThread1);

 

     return 0;

}

 


 

 

WaitForSingleObject将阻塞当前线程直到线程MyThread结束后返回

 

// MyThread.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

#include <windows.h>

#include <commctrl.h>

 

 

DWORD MyThread(PVOID pArg)

{

     INT32 nParam = (INT32)pArg;

 

     printf("nParam:%d/n",nParam);   

 

     return 0;

}

 

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

{

     HANDLE hThread1;

     DWORD dwThreadID = 0;

     INT32 nParameter = 10;

 

     hThread1 = CreateThread(NULL, 0, MyThread,(PVOID)nParameter, 0, &dwThreadID);

     if(hThread1)  {

         printf("CreateThread MyThread success/r/n");

     }    else {

         printf("CreateThread MyThread error/r/n");

         return -1;

     }   

    

     WaitForSingleObject(hThread1, INFINITE);

    

     CloseHandle(hThread1);

 

     return 0;

}

原创粉丝点击