C++多线程二

时间:2021-06-07 20:25:15

SuspendThread()暂停一个线程,ResumeThread()重启一个线程。参数均为线程的句柄。

#include <iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI mythread(void *p)
{
for(int i=;i<;i++)
{
cout<<"hello,everybody!"<<endl;
::Sleep();
}
return ;
} int main()
{
HANDLE handle;
DWORD dw;
handle=::CreateThread(NULL,,mythread,NULL,,&dw);
::Sleep();
for(int i=;i<;i++)
{
cout<<"---now,suspended!----"<<endl;
::SuspendThread(handle); //暂停
for(int j=;j<;j++)
{
cout<<"good,thank you!"<<endl;
::Sleep();
}
cout<<"----now,resumed!----"<<endl;
::ResumeThread(handle); //重启
::Sleep();
}
::CloseHandle(handle);
return ;
}

TerminateThread()终止一个线程,两个参数(线程的句柄,线程的退出码)。此函数比较危险,被终止的线程函数立马停止执行,无法释放相关资源。

DWORD WINAPI mythread(void *lp)
{
for(int i=;i<;i++)
{
cout<<"hello"<<endl;
::Sleep();
}
return ;
} int main()
{
HANDLE handle;
DWORD dw;
handle=::CreateThread(NULL,,mythread,NULL,,&dw);
if(handle==NULL)
{
cout<<"thread failed!"<<endl;
return -;
}
::Sleep();
cout<<"thread terminated!"<<endl;
::TerminateThread(handle,);//终止线程的执行
::Sleep();
::CloseHandle(handle);
return ;
}

GetExitCodeThread()用来查询某个线程的退出码。如果线程还在运行,返回STILL_ACTIVE;如果已经结束,则返回由TerminateThread()或ExitThread()设置的退出码。

DWORD WINAPI mythread(void *p)
{
cout<<"mythread id is:"<<::GetCurrentThreadId()<<endl;
return ;
}
//分别输出线程ID和线程退出码
int main()
{
HANDLE handle;
DWORD dw;
handle=::CreateThread(NULL,,mythread,NULL,,&dw);
::Sleep();
::GetExitCodeThread(handle,&dw);
cout<<"thread exitCode is:"<<dw<<endl;
return ;
}

ExitThread()退出线程,并释放相关的资源。参数为线程的退出码。

DWORD WINAPI mythread(void *p)
{
cout<<"mythread id is :"<<::GetCurrentThreadId()<<endl;
cout<<"thread exit!"<<endl;
::ExitThread();//参数即为线程的退出码
cout<<"不能执行到这里"<<endl;
return ;
}
int main()
{
HANDLE handle;
DWORD dw;
handle=::CreateThread(NULL,,mythread,NULL,,&dw);
::Sleep();
::GetExitCodeThread(handle,&dw);
cout<<"thread id is :"<<dw<<endl;
::CloseHandle(handle);
return ;
}

BOOL WINAPI SetThreadPriority(HANDLE hThread,int nPriority)设置线程的优先级。

//(线程句柄,要设置的优先级)

Int WINAPI GetThreadPriority(HANDLE hThread);获得线程的优先级。