Code:
#include <iostream>
#include <windows.h>
#include <thread>
using namespace std;
int input(int time, int *ptr)
{
int sec = 0, flag = 0;
thread t1([&]()
{
cin >> *ptr;
sec = 0;
flag = 1;
t1.detach();
});
thread t2([&]()
{
while (flag == 0)
{
if (sec == time)
{
if (t1.joinable())
{
t1.detach();
}
break;
}
Sleep(1000);
sec++;
}
});
t2.join();
return flag;
}
int start(int time, int *ptr)
{
return input(time, ptr);
}
int main()
{
int arr[10], flag2 = 1, count = 0;
for (int i = 0; i < 10; i++)
{
cout << "Enter " << i + 1 << " element: ";
flag2 = start(2, arr + i);
if (flag2 == 0)
{
cout << endl;
break;
}
count++;
}
cout << endl
<< "Array elements: ";
for (int i = 0; i < count; i++)
{
cout << *(arr + i) << " ";
}
int temp;
cout << "\nEnter temporary value: ";
cin >> temp;
cout << "Here is what you gave as input: " << temp;
return 0;
}
Output:
Enter 1 element: 5
Enter 2 element: 2
Enter 3 element: 6
Enter 4 element: 8
Enter 5 element:
Array elements: 5 2 6 8
Enter temporary value: 7
terminate called after throwing an instance of 'std::system_error'
what(): No such process
Expected output:
Enter 1 element: 5
Enter 2 element: 2
Enter 3 element: 6
Enter 4 element: 8
Enter 5 element:
Array elements: 5 2 6 8
Enter temporary value: 7
Here is what you gave as input: 7
Code overview: Above code takes array input from user until user wants to stop, like I want to take infinite input from user, for linked list/stack/queue, I know that array has fixed size, but my problem is not with taking infinite input, that works fine, I used two thread one thread (timer t2) for counting seconds (in this case 2 seconds) and another (input t1) to take input from user. When user finished giving input he just need to wait for 2 seconds and thread t2 will detach thread t1, and now here comes the problem.
Problem: Everything is right till line 59, but then when I try to take input for 'temp' an exception occurs, terminate called after throwing an instance of 'std::system_error' what(): No such process. As I said before about my code, I am taking pointer from user and storing value at that address. But, when user stopped giving input and thread t2 detached t1, then code resumes, no problem till here but input of cin inside thread t1 remain incomplete, it requires an input, hence when I give input for 'temp' it takes it for my previous input inside thread t1 which was detached by thread t2 without taking input, I think, since that thread is no longer attached to main thread, this exception comes.
Is there any solution available for this? I tried a lot but failed, please review my code.
Any help will be appreciated.
In your case you should use atomic shared variables across threads.
The std::cin
is blocking operation. In your code two seconds later doing detach for thread1. But std::cin
still waiting for input...
The console window can std::cin
or std::cout
but not both at the same time so you need to change algorithm to avoid this problem.