提前结束c++线程
End c++ Thread Early
这是我的简单示例
#include <iostream>
#include <windows.h>
#include <thread>
using namespace std;
int x, counter;
int zero = 0;
void example()
{
x = 1;
cin >> x;
}
int main()
{
do
{
thread T1(example);
Sleep(10);
if (x == 1)
{
counter++;
}
else
{
//kill thread without calling abort()
}
} while (zero == 0);
}
我的问题是,如果 cin 在 10 毫秒内没有 return 值,我希望它退出线程。我试过 T1.join()
之类的东西,但那只是等待它结束。如果我跳过 T1.join()
并且循环自行重新启动系统调用 abort()
..
那么如何在不调用 std::terminate()
或 abort()
的情况下安全地结束线程?
PS:请尽量简单地回答,不要使用任何高级技术,因为我对 C++ 还很陌生。也请尝试解释您的答案中的所有内容,因为我查找的大多数答案都有我不理解和无法理解的东西,例如 Atomic bool
我无法理解,所以我无法实现
我通过使用 detach 然后使用 deconstruct ~
东西修复了它。
这是我的做法:
void IOLogic()
{
exitkey = false;
cout << ">>";
cin >> key;
switch (key)
{
case 'a': direction = 1;
break;
case 'd': direction = 3;
break;
case 's': direction = 2;
break;
case 'x': GameEnd = true;
break;
case '0': direction = 2;
break;
}
exitkey = true;
}
thread mainLogic(IOLogic);
Sleep(1500);
if (exitkey == true)
{
mainLogic.detach();
}
else
{
mainLogic.detach();
mainLogic.~thread();
system("cls");
}
这是我的简单示例
#include <iostream>
#include <windows.h>
#include <thread>
using namespace std;
int x, counter;
int zero = 0;
void example()
{
x = 1;
cin >> x;
}
int main()
{
do
{
thread T1(example);
Sleep(10);
if (x == 1)
{
counter++;
}
else
{
//kill thread without calling abort()
}
} while (zero == 0);
}
我的问题是,如果 cin 在 10 毫秒内没有 return 值,我希望它退出线程。我试过 T1.join()
之类的东西,但那只是等待它结束。如果我跳过 T1.join()
并且循环自行重新启动系统调用 abort()
..
那么如何在不调用 std::terminate()
或 abort()
的情况下安全地结束线程?
PS:请尽量简单地回答,不要使用任何高级技术,因为我对 C++ 还很陌生。也请尝试解释您的答案中的所有内容,因为我查找的大多数答案都有我不理解和无法理解的东西,例如 Atomic bool
我无法理解,所以我无法实现
我通过使用 detach 然后使用 deconstruct ~
东西修复了它。
这是我的做法:
void IOLogic()
{
exitkey = false;
cout << ">>";
cin >> key;
switch (key)
{
case 'a': direction = 1;
break;
case 'd': direction = 3;
break;
case 's': direction = 2;
break;
case 'x': GameEnd = true;
break;
case '0': direction = 2;
break;
}
exitkey = true;
}
thread mainLogic(IOLogic);
Sleep(1500);
if (exitkey == true)
{
mainLogic.detach();
}
else
{
mainLogic.detach();
mainLogic.~thread();
system("cls");
}