将C ++中的std :: thread线程转换或转换为Windows中的HANDLE是否可行? 我一直在尝试使用线程的WINAPI函数来管理Windows中的线程,但我无法让它工作......
#include <thread>
#include <string>
#include <iostream>
#include <windows.h>
void Hi(std::string n){
while(true){
std::cout<<"Hi :3 "<<n<<"\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main(void){
std::thread first(Hi, "zoditu");
first.detach();
getc(stdin);
//SuspendThread((void*)first.native_handle());
TerminateThread((void*)first.native_handle(), (unsigned long)0x00);
CloseHandle((void*)first.native_handle());
std::cout<<"No D:!!\n";
getc(stdin);
return 0;
}
但似乎什么也没做,因为线程一直在控制台中产生“嗨”......有没有办法用WINAPI“杀死”它?
答案 0 :(得分:1)
我认为使用std::thread::native_handle()
直接使用Win32 API函数返回的值没有任何问题(即,不需要转换)。
以下程序适合我。 然而,它通常(总是?)崩溃,如果线程在它正在执行时被终止但是如果线程在终止之前被挂起则工作正常。如您所知,其他人已经指出终止线程通常不是一个好主意。
但回答你的问题 Win32 API似乎按预期工作,无需任何额外的转换。以下程序适合我。
#include <windows.h>
#include <iostream>
#include <string>
#include <thread>
void foo()
{
while (true)
{
std::cout << "foo()\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main(void)
{
std::thread first(foo);
bool isFinished = false;
while (!isFinished)
{
char ch = ::getchar();
::getchar(); // Swallow the new line character
if (ch == 'e')
{
isFinished = true;
}
else if (ch == 's')
{
DWORD result = ::SuspendThread(first.native_handle());
if (result != -1)
{
std::cout << "Successfully suspended thread\n";
}
else
{
std::cout << "Failed to suspend thread: failure resson " << ::GetLastError() << "\n";
}
}
else if (ch == 'r')
{
DWORD result = ::ResumeThread(first.native_handle());
if (result != -1)
{
std::cout << "Successfully resumed thread\n";
}
else
{
std::cout << "Failed to resume thread: failure resson " << ::GetLastError() << "\n";
}
}
else if (ch == 'k')
{
DWORD result = ::TerminateThread(first.native_handle(), 1);
if (result != 0)
{
std::cout << "Successfully terminated thread\n";
}
else
{
std::cout << "Failed to terminate thread: failure resson " << ::GetLastError() << "\n";
}
}
else
{
std::cout << "Unhandled char '" << ch << "'\n";
}
}
first.detach();
std::cout << "waiting to exit main...";
::getchar();
std::cout << "exiting...\n";
return 0;
}
foo()
foo()
foo()
foo()
s
Successfully suspended thread // This was successful since 'foo()' is no longer printing
r
Successfully resumed thread // This was successful since 'foo()' is again printing
foo()
foo()
foo()
foo()
s
Successfully suspended thread // Worked again
k
Successfully terminated thread // Says it works...
r
Successfully resumed thread // Termination must have worked because resuming did not cause 'foo' to start printing
e
waiting to exit main...
exiting...