工控编程吧
标题:
234上位机VC MFC实现线程的优先执行
[打印本页]
作者:
qq263946146
时间:
2016-3-1 21:56
标题:
234上位机VC MFC实现线程的优先执行
(, 下载次数: 3)
上传
点击文件名下载附件
234上位机VC MFC实现线程的优先执行
功能展示
多个线程对相同资源访问时有优先权的设置,比如我们在一边听着音乐,一边浏览网页时,这时就可以把执行音乐播放任务的线程执行级别设置高一点,这样可以不让音乐听起来断断续续,我们当前例程实现七个不同优先级别线程向编辑框写入文本,效果如图,点击七个按钮,启动七个不同级别线程,线程以各自的优先级别向编辑框写入文本;
要点提示
线程的优先级别可以使用函数SetThreadPriority();
函数原型:BOOLWINAPI SetThreadPriority(HANDLE hThread,in int nPriority);
hThread是线程的句柄。nPriority是线程的优先级;共有七级别分别为:
THREAD_PRIORITY_IDLE(最低)
THREAD_PRIORITY_LOWEST(低)
THREAD_PRIORITY_BELOW_NORMAL( 低于标准)
THREAD_PRIORITY_NORMAL(标准)
THREAD_PRIORITY_ABOVE_NORMAL(高于标准)
THREAD_PRIORITY_HIGHEST(高)
THREAD_PRIORITY_TIME_CRITICAL(最高)
实现功能
1.新建基于对话框的应用程序
2.拖拽一编辑框ID为IDC_EDIT1,和七个按钮关联按钮函数
void CGkbc8Dlg::OnButton5()
{
HANDLE h5;
h5=CreateThread(NULL,0,ThreadFun,(LPVOID)this,CREATE_SUSPENDED,&wID5);
SetThreadPriority(h5,THREAD_PRIORITY_ABOVE_NORMAL);//+1(在原有基础上+1)
ResumeThread(h5);
}
void CGkbc8Dlg::OnButton6()
{
HANDLE h6;
h6=CreateThread(NULL,0,ThreadFun,(LPVOID)this,CREATE_SUSPENDED,&wID6);
SetThreadPriority(h6,THREAD_PRIORITY_HIGHEST);//+2(在原有基础上+2)
ResumeThread(h6);
}
void CGkbc8Dlg::OnButton7()
{
HANDLE h7;
h7=CreateThread(NULL,0,ThreadFun,(LPVOID)this,CREATE_SUSPENDED,&wID7);
SetThreadPriority(h7,THREAD_PRIORITY_TIME_CRITICAL);//如果进程优先级为realtime则调整为31,其它情况为15
ResumeThread(h7);
}
void CGkbc8Dlg::OnButton4()
{
HANDLE h4;
h4=CreateThread(NULL,0,ThreadFun,(LPVOID)this,CREATE_SUSPENDED,&wID4);
SetThreadPriority(h4,THREAD_PRIORITY_NORMAL);//不变(取进程优先级值)
ResumeThread(h4);
}
复制代码
void CGkbc8Dlg::OnButton1()
{
HANDLE h1;
h1=CreateThread(NULL,0,ThreadFun,(LPVOID)this,CREATE_SUSPENDED,&wID1);
SetThreadPriority(h1,THREAD_PRIORITY_IDLE);//如果进程优先级为realtime则调整为16,其它情况为1
ResumeThread(h1);//<>执行线程
}
void CGkbc8Dlg::OnButton2()
{
HANDLE h2;
h2=CreateThread(NULL,0,ThreadFun,(LPVOID)this,CREATE_SUSPENDED,&wID2);
SetThreadPriority(h2,THREAD_PRIORITY_LOWEST);//-2(在原有基础上-2)
ResumeThread(h2);
}
void CGkbc8Dlg::OnButton3()
{
HANDLE h3;
h3=CreateThread(NULL,0,ThreadFun,(LPVOID)this,CREATE_SUSPENDED,&wID3);
SetThreadPriority(h3,THREAD_PRIORITY_BELOW_NORMAL);//-1(在原有基础上-1)
ResumeThread(h3);
}
复制代码
3.添加向编辑框写入文本的自定义函数函数ShowText();
4.在主对话框源文顶部添加线程函数ThreadFun();
DWORD wID1,wID2,wID3,wID4,wID5,wID6,wID7;
DWORD WINAPI ThreadFun(LPVOID pParam)
{
CGkbc8Dlg* pDlg=(CGkbc8Dlg*)pParam;
DWORD wID=GetCurrentThreadId();
if(wID==wID1)
pDlg->ShowText(1);
else if(wID==wID2)
pDlg->ShowText(2);
else if(wID==wID3)
pDlg->ShowText(3);
复制代码
else if(wID==wID4)
pDlg->ShowText(4);
else if(wID==wID5)
pDlg->ShowText(5);
else if(wID==wID6)
pDlg->ShowText(6);
else if(wID==wID7)
pDlg->ShowText(7);
return 0;
}
复制代码
我们来演示下功能实现的整个过程
[iqiyi]http://player.video.qiyi.com/6d4a8a49f8e99d95cdf2debf8edfa20d/0/0/w_19rsxfzww1.swf-albumId=5506974509-tvId=5506974509-isPurchase=0-cnId=12[/iqiyi]
(, 下载次数: 0)
上传
点击文件名下载附件
[note]1[/note]
欢迎光临 工控编程吧 (https://www.gkbc8.com/)
Powered by Discuz! X3.4