Boost threads; how do I get a thread to yield after a specified amount of time

Boost threads; how do I get a thread to yield after a specified amount of time

This is a discussion on Boost threads; how do I get a thread to yield after a specified amount of time within the C++ Programming forums, part of the General Programming Boards category; I'm trying to get into boost threads but I'm at a loss by examples and challenges by which to learn, ...

Boost threads; how do I get a thread to yield after a specified amount of time

I'm trying to get into boost threads but I'm at a loss by examples and challenges by which to learn, so I was trying to remember an example in my java course where a user is prompted for a password, and if they don't enter it and allow the thread to complete normally the thread ends. I was trying to recreate this but it doesn't seem to be working. I know what mutexes do but I don't know if I'm using the right strategy. How do I get a thread to "time out"?

Firstly, within your "while (attempt != pass)" loop you need to check if the time limit has expired. When the time limit expires, break out (preferably without granting access).

Second, operations on cin do not time out. You will need to use some technique, such as checking if there is data to be read from cin as well as checking for timeout, before actually attempting to read from cin.

Third, multi threading is not necessary to do this (and is probably unnecessarily complex).

There is no way in standard C++ to abort an I/O operation. Nor does Boost currently support it. Once Boost.Asio adds support for file I/O, you could start an async operation and cancel it on timeout, but that's not yet reality.

It's hard to come up with simple examples. You use multithreading mostly to
1) move long-running computations out of a thread that must stay responsive for UI or some other purpose
2) take advantage of multiple cores/CPUs in data processing, in which case you would typically split up your data and set each thread to working on a bit of it.

No! Lock objects are not meant to be shared between threads. They are meant to be short-lived objects created on automatic storage within a code block. Any other usage is just likely to lead to errors and won't really be of actual benefit anyway. Share Mutexes, not Locks. For more information see the rationale behind the design for lock objects.

The Lock is basically just a helper object which enforces RAII for locking Mutex objects. So when the Lock goes out of scope, the Mutex is automatically unlocked.

In many other threading paradigms the words "Mutex" and "Lock" are pretty much interchangeable, but not in Boost threads. A better name might have been "Key" instead of "Lock," since it is an object which locks something, not an object which is itself locked.

So, think "Key" not "Lock" and remember, many people may have keys to the same lock, but each person has their OWN key, they are not shared.