Hello I was trying to break the loop in middle of its execution.The loop shows a countdown of seconds from 5-1 .I want to break the loop in middle using any keystroke entered by the user.I researched for some time and created a thread. I set a global variable and updated it in the second thread. I gave a condition in the main function using that global variable but the loop doesn't break.
Here is the code.
Please help.
#include<iostream>
#include<windows.h>
#include<stdlib.h>
#include<iomanip>
#include<stdio.h>
using namespace std;
bool stop=false;
DWORD WINAPI thread1(LPVOID pm)
{
//check the getchar value
int a = getchar();
while (a != '0'){
a = getchar();
}
stop = true;
return 0;
}
int main()
{
HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
for(int i=5;i>0 && !stop;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
system("PAUSE");
}
The program counts down and in middle of the count down i tried to break the loop.thread1 function takes an input and modifies stop(global variable). But the loop in main function doesn't break(it should).Loop goes on decreasing loop variable, becomes zero and loop ends.
You have to declare stop as volatile
volatile bool stop
It informs compiler not optimized (by cache) access to variable, because another thread can modify it.
Also, take care about read and write access on global variable by many thread : in most of case, you have to protect them using mutex. (I think in your case it's not necessary according basic small type and basic access, but take care)
EDIT
As ask in comments, this is my design when inverting thread :
#include<iostream>
#include<windows.h>
#include<stdlib.h>
#include<iomanip>
#include<stdio.h>
using namespace std;
volatile bool stop = false;
DWORD WINAPI thread1(LPVOID pm)
{
for(int i=5;i>0 && !stop;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
return 0;
}
int main()
{
HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
//check the getchar value
int a = getchar();
while (a != '0'){
a = getchar();
}
stop = true;
WaitForSingleObject(handle, INFINITE);
system("PAUSE");
}
With this solution, it will stop after waiting 1s. If you want to terminate immediatly, you can use TerminateThread but read this before : https://msdn.microsoft.com/en-us/library/windows/desktop/ms686717%28v=vs.85%29.aspx
Found it. getchar() was waiting for carriage return. So i used _getch() from conio library. Like this.
#include<iostream>
#include<Windows.h>
#include<conio.h>
#include<stdlib.h>
#include<iomanip>
using namespace std;
volatile bool stop = false;
DWORD WINAPI thread1(LPVOID pm)
{
int a = 0;
while (a==0)
{
a = _getch();
}
stop = true;
return 0;
}
int main()
{
HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
int i;
for ( i = 5; i > 0 && !stop; i--)
{
cout << "\n\n\n\n\n\n";
cout << setw(35);
cout << i;
Sleep(1000);
system("CLS");
}
if (i != 0)
cout << "Loop broken sucessflly.\n";
else
cout << "Attempt failed\n";
system("PAUSE");
}
Related
So I was making an application using C++ Console, with multi threading as below, then I got an error 0x0000005.
The first time it run it was working as usual. Can anyone help me with this problem?
I am using Code::Blocks IDE with Borland C++ 5.5, and I am planning to make this into Borland C++ 5.02
#include <windows.h>
#include <stdio.h>
#include <dos.h>
#include <iostream.h>
#include <conio.h>
void linesmov(int mseconds, int y);
void linesmov(int mseconds, int y)
{
int i=0;
while (true)
{
i=i+1;
// Or system("cls"); If you may...
gotoxy(i,y);
cout << "____||____||____";
gotoxy(i-1,y);
cout << " ";
Sleep(mseconds);
if (i>115)
{
i=0;
for(int o = 0; o < 100; o++)
{
gotoxy(0,y);
cout << " ";
}
}
}
}
DWORD WINAPI mythread1(LPVOID lpParameter)
{
printf("Thread inside %d \n", GetCurrentThreadId());
linesmov(5,10);
return 0;
}
DWORD WINAPI mythread2(LPVOID lpParameter)
{
printf("Thread inside %d \n", GetCurrentThreadId());
linesmov(30,15);
return 0;
}
int main(int argc, char* argv[])
{
HANDLE myhandle1;
DWORD mythreadid1;
HANDLE myhandle2;
DWORD mythreadid2;
myhandle1 = CreateThread(0,0,mythread1,0,0,&mythreadid1);
myhandle2 = CreateThread(0,0,mythread2,0,0,&mythreadid2);
printf("Thread after %d \n", mythreadid1);
getchar();
return 0;
}
All of these solutions in comments including mine are definitely not the way how it should be done. The main problem is lack of synchronization between threads and lack of processing their termination. Also, every function should be checked for thread-safe compatibility or should be wrapped to match it.
Considering std::cout since c++11 we have some data race guarantees:
Concurrent access to a synchronized (§27.5.3.4) standard iostream
object’s formatted and unformatted input (§27.7.2.1) and output
(§27.7.3.1) functions or a standard C stream by multiple threads shall
not result in a data race (§1.10). [ Note: Users must still
synchronize concurrent use of these objects and streams by multiple
threads if they wish to avoid interleaved characters. — end note ]
So lask of synchronization primitives is oblivious according to this note.
Considering processing of thread termination.
HANDLE threadH = CreateThread(...);
...
TerminateThread(threadH, 0); // Terminates a thread.
WaitForSingleObject(threadH, INFINITE); // Waits until the specified object is in the signaled state or the time-out interval elapses.
CloseHandle(threadH); // Closes an open object handle.
TerminateThread(), but be aware of this solution, because ..
WaitForSingleObject()
And this is only first steps to thread-safe way.
I would like to recommend C++ Concurrency in Action: Practical Multithreading by Anthony Williams for further reading.
Rude solution for synchronized output
#include <Windows.h>
#include <iostream>
#include <mutex>
std::mutex _mtx; // global mutex
bool online = true; // or condition_variable
void gotoxy(int x, int y)
{
COORD c = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void linesmov(int mseconds, int y) {
int i = 0;
while (online) {
i = i + 1;
// Or system("cls"); If you may...
_mtx.lock(); // <- sync here
gotoxy(i, y);
std::cout << "____||____||____"; gotoxy(i - 1, y);
std::cout << " ";
_mtx.unlock();
Sleep(mseconds);
if (i > 75)
{
i = 0;
for (int o = 0; o < 60; o++)
{
_mtx.lock(); // <- sync here
gotoxy(0, y);
std::cout << " ";
_mtx.unlock();
}
}
}
}
DWORD WINAPI mythread1(LPVOID lpParameter)
{
std::cout << "Thread 1" << GetCurrentThreadId() << std::endl;
linesmov(5, 10);
return 0;
}
DWORD WINAPI mythread2(LPVOID lpParameter)
{
std::cout << "Thread 2" << GetCurrentThreadId() << std::endl;
linesmov(30, 15);
return 0;
}
int main(int argc, char* argv[])
{
DWORD mythreadid1;
DWORD mythreadid2;
HANDLE myhandle1 = CreateThread(0, 0, mythread1, 0, 0, &mythreadid1);
HANDLE myhandle2 = CreateThread(0, 0, mythread2, 0, 0, &mythreadid2);
std::cout << "Base thread: " << GetCurrentThreadId() << std::endl;
getchar();
online = false;
WaitForSingleObject(myhandle1, INFINITE);
WaitForSingleObject(myhandle2, INFINITE);
CloseHandle(myhandle1);
CloseHandle(myhandle2);
return 0;
}
a) Both gotoxy not outputting via std::cout are not thread safe /synchronized. You need process-wide mutex to synchronize that
b) exception is likely due to fact that you do not use WaitForMultipleObjects in main to wait for threads to finish. Depending on hardware and optimization main may exit before threads finish their work.
I want to run a separate thread to close the program when user press a specific key. This is the structure of my program.
#include <iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI foo(LPVOID lpParameter)
{
//do something
return 0;
}
DWORD WINAPI boo(LPVOID lpParameter)
{
//do something
return 0;
}
int main(int argc, char **argv)
{
HANDLE foo1,boo1;
while(true)
{
foo1 = CreateThread(NULL,0,foo,NULL,0,NULL);
boo1= CreateThread(NULL,0,boo,NULL,0,NULL);
//do something
}
return 0;
}
I have created two threads inside of always true while loop to keep the program running . So I want to add another thread to get user input whenever user press a key (while program is running) and after comparing it with specific already defined character, if they match close the program.
I have no idea of doing that.Can someone help me?
PS : I have to do that using threads only :)
You are not creating two threads. You are creating threads in an infinite loop until you run out of memory. Besides, your main is already running on a separate thread, so you can do your user input there. For example:
HANDLE hevent = NULL;
bool done = false;
DWORD WINAPI foo(LPVOID lpParameter)
{
while(!done)
{
::WaitForSingleObject(hevent, -1);
printf("\rfoo");
Sleep(1000);
::ResetEvent(hevent);
}
return 0;
}
DWORD WINAPI boo(LPVOID lpParameter)
{
while(!done)
{
printf("\rboo");
Sleep(1000);
SetEvent(hevent);
}
return 0;
}
int main(int argc, char **argv)
{
HANDLE foo1,boo1;
hevent = CreateEvent(NULL, TRUE, TRUE, NULL);
foo1 = CreateThread(NULL,0,foo,NULL,0,NULL);
boo1= CreateThread(NULL,0,boo,NULL,0,NULL);
HANDLE handles[] = {foo1, boo1};
char c = getchar();
done = true;
::WaitForMultipleObjects(2, handles, TRUE, -1);
return 0;
}
I am trying something like this.Its counting down seconds from 5-1.
#include<iostream>
#include<stdlib.h>
#include<windows.h>
#include<iomanip>
using namespace std;
int main()
{
for(int i=5;i>0;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
system("PAUSE");
}
And i trying to figure out a way to break the loop using a user input(from keyboard) to break it while its running. I have no idea about how to do this.I have heard about multi-threading. I don't even know if multi-threading has any application in my situation or not .So any ideas on how to break it in middle while its executing the loop?
I think you will need a thread to do it.
add a global variable in your main loop,
use a thread to receive the command line input and modify your global variable.
declare a global variable
bool stop = false;
create a thread to read stdin and modify 'stop'
DWORD WINAPI thread1(LPVOID pm)
{
//check the getchar value
int a = getchar();
while (a != '0'){
a = getchar();
}
stop = true;
return 0;
}
in your main:
HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
for(int i=5;i>0 && !stop;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
Try this:
#include<iostream>
using namespace std;
int main()
{
int i = 1;
while(i)
{
// do your work here
cin>>i;
}
cout<<"Terminated"<<endl;
}
Continue scanning int i, when you want to break loop give 0 as input value and your loop will be terminatd.
I'm a beginner and I'm trying to reproduce a rae condition in order to familirize myself with the issue. In order to do that, I created the following program:
#include <Windows.h>
#include <iostream>
using namespace std;
#define numThreads 1000
DWORD __stdcall addOne(LPVOID pValue)
{
int* ipValue = (int*)pValue;
*ipValue += 1;
Sleep(5000ull);
*ipValue += 1;
return 0;
}
int main()
{
int value = 0;
HANDLE threads[numThreads];
for (int i = 0; i < numThreads; ++i)
{
threads[i] = CreateThread(NULL, 0, addOne, &value, 0, NULL);
}
WaitForMultipleObjects(numThreads, threads, true, INFINITE);
cout << "resulting value: " << value << endl;
return 0;
}
I added sleep inside a thread's function in order to reproduce the race condition as, how I understood, if I just add one as a workload, the race condition doesn't manifest itself: a thread is created, then it runs the workload and it happens to finish before the other thread which is created on the other iteration starts its workload. My problem is that Sleep() inside the workload seems to be ignored. I set the parameter to be 5sec and I expect the program to run at least 5 secs, but insted it finishes immediately. When I place Sleep(5000) inside main function, the program runs as expected (> 5 secs). Why is Sleep inside thread unction ignored?
But anyway, even if the Sleep() is ignored, the program outputs this everytime it is launched:
resulting value: 1000
while the correct answer should be 2000. Can you guess why is that happening?
WaitForMultipleObjects only allows waiting for up to MAXIMUM_WAIT_OBJECTS (which is currently 64) threads at a time. If you take that into account:
#include <Windows.h>
#include <iostream>
using namespace std;
#define numThreads MAXIMUM_WAIT_OBJECTS
DWORD __stdcall addOne(LPVOID pValue) {
int* ipValue=(int*)pValue;
*ipValue+=1;
Sleep(5000);
*ipValue+=1;
return 0;
}
int main() {
int value=0;
HANDLE threads[numThreads];
for (int i=0; i < numThreads; ++i) {
threads[i]=CreateThread(NULL, 0, addOne, &value, 0, NULL);
}
WaitForMultipleObjects(numThreads, threads, true, INFINITE);
cout<<"resulting value: "<<value<<endl;
return 0;
}
...things work much more as you'd expect. Whether you'll actually see results from the race condition is, of course, a rather different story--but on multiple runs, I do see slight variations in the resulting value (e.g., a low of around 125).
Jerry Coffin has the right answer, but just to save you typing:
#include <Windows.h>
#include <iostream>
#include <assert.h>
using namespace std;
#define numThreads 1000
DWORD __stdcall addOne(LPVOID pValue)
{
int* ipValue = (int*)pValue;
*ipValue += 1;
Sleep(5000);
*ipValue += 1;
return 0;
}
int main()
{
int value = 0;
HANDLE threads[numThreads];
for (int i = 0; i < numThreads; ++i)
{
threads[i] = CreateThread(NULL, 0, addOne, &value, 0, NULL);
}
DWORD Status = WaitForMultipleObjects(numThreads, threads, true, INFINITE);
assert(Status != WAIT_FAILED);
cout << "resulting value: " << value << endl;
return 0;
}
When things go wrong, make sure you've asserted the return value of any Windows API function that can fail. If you really badly need to wait on lots of threads, it is possible to overcome the 64-thread limit by chaining. I.e., for every additional 64 threads you need to wait on, you sacrifice a thread whose sole purpose is to wait on 64 other threads, and so on. We (Windows Developer's Journal) published an article demonstrating the technique years ago, but I can't recall the author name off the top of my head.
This question already has answers here:
How to check if a process is running or not using C++
(3 answers)
Closed 9 years ago.
Hi iuse this code for check Process after my App "piko.exe" run and if the programs such as
"non.exe","firefox.exe","lol.exe" if running closed my App and return an error.
But i need to this check process every 30 sec and i used while but my main program (this code is one part of my project) stopped working so pleas if possible pls someone edited my code thank you.
#include "StdInc.h"
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <stdio.h>
void find_Proc(){
HANDLE proc_Snap;
HANDLE proc_pik;
HANDLE proc_pikterm;
PROCESSENTRY32 pe32;
PROCESSENTRY32 pe32pik;
int i;
char* chos[3] = {"non.exe","firefox.exe","lol.exe"};
char* piko = "piko.exe";
proc_pik = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
proc_Snap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
pe32.dwSize = sizeof(PROCESSENTRY32);
pe32pik.dwSize = sizeof(PROCESSENTRY32);
for(i = 0; i < 3 ; i++){
Process32First(proc_Snap , &pe32);
do{
if(!strcmp(chos[i],pe32.szExeFile)){
MessageBox(NULL,"CHEAT DETECTED","ERROR",NULL);
Process32First(proc_pik,&pe32pik);
do{
if(!strcmp(iw4m,pe32pik.szExeFile)){
proc_pikterm = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pe32pik.th32ProcessID);
if(proc_pikterm != NULL)
TerminateProcess(proc_pikterm, 0);
CloseHandle(proc_pikterm);
}
} while(Process32Next(proc_pik, &pe32pik));
}
} while(Process32Next(proc_Snap, &pe32));
}
CloseHandle(proc_Snap);
CloseHandle(proc_pik);
}
Based on what OS you're using you can poll the system time and check to see if 30 seconds have expired. The way to do so is to take the time at the beginning of your loop, take the time at the end and subtract them. Then subtract the time you want to sleep from the time it took your code to run that routine.
Also, if you don't need EXACTLY 30 seconds, you could just add sleep(30) to your loop.
Can you explain to me why this method wouldn't work for you? The code below is designed to count up one value each second. Make "checkMyProcess" do whatever you need it to do within that while loop before the sleep call.
#include <iostream>
using namespace std;
int someGlobal = 5;//Added in a global so you can see what fork does, with respect to not sharing memory!
bool checkMyProcess(const int MAX) {
int counter = 0;
while(counter < MAX) {
cout << "CHECKING: " << counter++ << " Global: " << someGlobal++ << endl;
sleep(1);
}
}
void doOtherWork(const int MIN) {
int counter = 100;
while(counter > MIN) {
cout << "OTHER WORK:" << counter-- << " Global: " << someGlobal << endl;
sleep(1);
}
}
int main() {
int pid = fork();
if(pid == 0) {
checkMyProcess(5);
} else {
doOtherWork(90);
}
}
Realize of course that, if you want to do work outside of the while loop, within this same program, you would have to use threading, or fork a pair of processes.
EDIT:
I added in a call to "fork" so you can see the two processes doing work at the same time. Note: if the "checkMyProcess" function needs to know something about the memory going on in the "doOtherWork" function threading will be a much easier solution for you!