Stack Overflow Asked by Lordi1000 on December 11, 2021
I have an app that plays a game for me, and it required me to make a thread which constantly scans my health and moves the character to a spot, if I go under that health. When the game is finished, it starts a new one, and then it creates a new thread which scans for health. Total of 2, of the same thread. How can I make so only 1 of those threads is created?
This is the thread I’m creating:
void task1()
{
while (true)
{
cout << "T1!" << endl;
HWND hwndinGame = FindWindowA(0, ("Game")); // Updating data each loop.
GetWindowThreadProcessId(hwndinGame, &pID);
uintptr_t oBaseAddress = GetModuleBaseAddress(pID, L"Game.exe");
HANDLE inGameHandle = OpenProcess(PROCESS_VM_READ, 0, pID);
LocalPlayer = Reader.ReadVOID(inGameHandle, oBaseAddress, oLocalPlayer);
myMaxHealth = Reader.ReadFLOAT(inGameHandle, LocalPlayer, oObjMaxHealth);
myHealth = Reader.ReadFLOAT(inGameHandle, LocalPlayer, oObjHealth);
posX = Reader.ReadFLOAT(inGameHandle, LocalPlayer, oObjPosX);
posY = Reader.ReadFLOAT(inGameHandle, LocalPlayer, oObjPosY);
std::this_thread::sleep_for(chrono::milliseconds(100));
if (myHealth < myMaxHealth / 1.97)
{
Clicker.DirectInput('f');
liveGameO.move_to_lane_noA(liveGameO.AbleToGetPos);
Sleep(4000);
}
while (myHealth < myMaxHealth / 1.97 && posX < 6000 && posY < 6000)
{
Clicker.DirectInput('b');
Sleep(10000);
}
}
}
This is the place where the thread is created in main:
std::cout << "In Game! Sleeping for 10!" << endl;
std::thread t1(task1);
t1.detach();
Sleep(20000);
It’s in side a while loop, so for each run through, an additional thread is created which is what I am trying to avoid, I only want one of those threads, so my app doesnt crash sooner or later 🙂
Thank you!
You could use named mutex on Windows:
CreateMutexA(0, 0, "unique_mutext_name");
if(GetLastError() == ERROR_ALREADY_EXISTS) // already exist?
return -1; // quit
// program code
Answered by alex_noname on December 11, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP