I created a thread named thread which calls the function run(). Inside run, it's supposed to ask for user input. However, when I execute the program, it simply terminates. Is there a problem using cin with threads?
You have to make main() wait for the thread to terminate. The call to pthread_create() returns immediately, and the program terminates when main() returns.
Here's a demonstration (DO NOT DO THIS):
1 2 3 4 5 6 7 8 9 10 11
int main()
{ pthread_t thread;
pthread_create(&thread, NULL, run, NULL);
sleep(10);
}
void *run(void *ptr)
{ int nRate;
cout << "You have 10 seconds to answer" << endl;
cin >> nRate;
}
What you really need is to make main() wait exactly until the other thread has terminated. There is a function for this called pthread_join():
1 2 3 4 5 6 7 8 9 10 11
int main()
{ pthread_t thread;
pthread_create(&thread, NULL, run, NULL);
pthread_join(thread, NULL);
}
void *run(void *ptr)
{ int nRate;
cout << "Take as long as you want" << endl;
cin >> nRate;
}