如何在无限循环中启动和停止(切换)多个线程
How to start and stop (toggle) multiple threads in a infinite loop
我正在尝试找到一种解决方案来无限循环中启动和停止多个线程。
每个线程都应该是一个单独的任务,并且应该并行运行。线程在无限循环中启动,线程本身也处于无限循环中。每个循环都应该以"GetKeyState"停止,所以我应该能够切换线程。但是我无法启动例如 2 个线程(程序的功能(,因为 .join(( 阻止了执行,没有 .join((,线程不起作用。
你们有解决这个问题的可能方法吗?一个线程的切换开始等于线程无限循环的切换停止。
这是我尝试过的一些代码
#include <iostream>
#include <thread>
#include <Windows.h>
class KeyToggle {
public:
KeyToggle(int key) :mKey(key), mActive(false) {}
operator bool() {
if (GetAsyncKeyState(mKey)) {
if (!mActive) {
mActive = true;
return true;
}
}
else
mActive = false;
return false;
}
private:
int mKey;
bool mActive;
};
KeyToggle toggle(VK_NUMPAD1);
KeyToggle toggle2(VK_NUMPAD2);
void threadFunc() {
while (!toggle) {
std::cout << "Thread_1n";
}
}
void threadFunc2() {
while (!toggle2) {
std::cout << "Thread_2n";
}
}
int main()
{
bool bToggle = false;
bool bToggle2 = false;
std::thread t1;
std::thread t2;
while (!GetKeyState(VK_NUMPAD0)) {
if (toggle) {
bToggle = !bToggle;
if (bToggle) {
std::thread t1(threadFunc);
t1.join();
}
}
if (toggle2) {
bToggle2 = !bToggle2;
if (bToggle2) {
std::thread t2(threadFunc2);
t2.join();
}
}
}
}
具有@Someprogrammerdude思想
的解决方案
#include <iostream>
#include <thread>
#include <Windows.h>
#include <atomic>
std::atomic<bool> aToggle1 = false;
std::atomic<bool> aToggle2 = false;
std::atomic<bool> aToggleStopAll = false;
class KeyToggle {
public:
KeyToggle(int key) :mKey(key), mActive(false) {}
operator bool() {
if (GetAsyncKeyState(mKey)) {
if (!mActive) {
mActive = true;
return true;
}
}
else
mActive = false;
return false;
}
private:
int mKey;
bool mActive;
};
KeyToggle toggle(VK_NUMPAD1);
KeyToggle toggle2(VK_NUMPAD2);
void threadFunc() {
while(aToggleStopAll==false)
{
if(aToggle1) { std::cout << "Thread_1n"; }
}
}
void threadFunc2() {
while(aToggleStopAll==false)
{
if(aToggle2) { std::cout << "Thread_2n"; }
}
}
int main()
{
std::thread t1(threadFunc);
std::thread t2(threadFunc2);
while (!GetKeyState(VK_NUMPAD0)) {
if (toggle) {
aToggle1 = !aToggle1;
}
if (toggle2) {
aToggle2 = !aToggle2;
}
}
aToggleStopAll = true;
t1.join();
t2.join();
}
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 给定使用 C++ 或 C,我如何测量在 linux 下进行线程切换需要多长时间?可能吗?
- 线程和上下文切换C++
- 对于同一任务,线程的等待时间在 0 到 30000 微秒之间系统地切换
- 如何在无限循环中启动和停止(切换)多个线程
- 如何使用SFML 2.2切换OpenGL上下文的线程
- 如何在 Linux 上强制 g++ 在协程切换线程时更新线程指针(对于 TLS)
- 当任何子线程导致错误时,上下文切换到主线程
- 避免忙于等待,并在实时和非实时线程之间切换模式
- 减少具有相同优先级的线程之间的上下文切换
- Qt,多线程上下文切换与QRadioButtons
- Std::this_thread::sleep_for语言 - 是上下文切换到这个线程
- 如何知道何时发生线程上下文切换
- 在多线程应用程序中为注入的mprotect调用切换标志
- 是否有可能编写可以在HPX和c++ 1x线程之间切换的代码?
- 是否有可能检测到一个线程在Linux中被上下文切换[挂起]
- 线程本地和上下文切换