如何在无限循环中启动和停止(切换)多个线程

How to start and stop (toggle) multiple threads in a infinite loop

本文关键字:切换 线程 无限循环 启动      更新时间:2023-10-16

我正在尝试找到一种解决方案来无限循环中启动和停止多个线程。

每个线程都应该是一个单独的任务,并且应该并行运行。线程在无限循环中启动,线程本身也处于无限循环中。每个循环都应该以"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();
}