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

  1. #1
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901

    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"?

    Code:
    #include <string>
    #include <iostream>
    
    #include <boost/thread/thread.hpp>
    #include <boost/thread/mutex.hpp>
    #include <boost/bind.hpp>
    
    using std::cout;    using std::cin;
    using std::endl;    using std::string;
    
    boost::timed_mutex timedMutex;
    
    const string pass("somejunk");
    
    void login(string name)
    {
        boost::timed_mutex::scoped_lock (timedMutex, 200);
        string attempt;
        while(attempt != pass)
        {
            cout << "Enter the password " << name <<" : ";
            cin >> attempt;
        }
        cout << "Access Granted" << endl;
    }
    
    int main()
    {
        boost::thread athread(boost::bind(login, "Daniel"));
        athread.join();
    
        return 0;
    }
    Edit: I try to remove the join on the thread but it doesn't even execute before ending.
    Last edited by indigo0086; 07-17-2007 at 08:56 AM.

  2. #2
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    Mario

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Three issues for consideration.

    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).

  4. #4
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    I'm not using multithreads to do this particular exercise, it's just an example to learn the library. Doing simple things in a multithreaded way to understand it better.

    I understand the point though

  5. #5
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    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.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  6. #6
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    I see. the more I read into it there can be better multithreading examples, but I can't come up with many.

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    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.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Also you can take out the IO operations from the CPU hungry thread - so your calculations will not be delayed by the slow IO operations
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  9. #9
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    I see. Well I've found some more basic examples to work with threads. What I first was trying to do was have multiple threads execute a looping count out of order. So here's what I got
    Code:
    #include <string>
    #include <iostream>
    
    #include <boost/thread/thread.hpp>
    #include <boost/thread/mutex.hpp>
    #include <boost/thread/xtime.hpp>
    #include <boost/bind.hpp>
    
    using std::cout;    using std::cin;
    using std::endl;    using std::string;
    
    boost::mutex ioMutex;
    
    
    void count(int id)
    {
        for(int i = 0; i < 50; ++i)
        {
            boost::mutex::scoped_lock lk(ioMutex);
            cout << "THREAD " << id << ": " << i << endl;
        }
    }
    
    int main()
    {
        boost::thread_group tGroup;
        for(int i = 0; i < 4; ++i)
        {
           tGroup.create_thread(boost::bind(count, i));
        }
        tGroup.join_all();
    
        return 0;
    }
    I understand what is going on with my previous experience with java threads, the one thing I

    1. When I "call tGroup.join_all() is it to ensure that main doesn't terminate before all the other threads do, or just ensure that all threads terminate naturally?

    2. Why does the thread class throw a fit when I share a lock object with all threads. For example lk(ioMutex) would be declared globally, and each thread locks or unlock it as so.
    Code:
    lk.lock();
    for.....
    lk.unlock()
    Is this because during the execution, if lock is already locked, then a thread trying to obtain one gets an exception thrown at them, or becaus a lock object shouldn't be shared as such.

  10. #10
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    I found my own answer to the first
    http://www.boost.org/doc/html/thread/faq.html#id1746163
    Are lock objects thread safe?


    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.

  11. #11
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by indigo0086 View Post
    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.

  12. #12
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    I get it now.

  13. #13
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    one thing to add: never use cout from parallel threads, because it's not thread safe. you should prefer printf in this case.

  14. #14
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by pheres View Post
    one thing to add: never use cout from parallel threads, because it's not thread safe. you should prefer printf in this case.
    Where did you get this strange idea?
    http://msdn2.microsoft.com/en-us/lib...3b(VS.80).aspx
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  15. #15
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    http://gcc.gnu.org/ml/libstdc++/2004-10/msg00070.html
    http://209.85.135.104/search?q=cache...lnk&cd=6&gl=de
    http://209.85.135.104/search?q=cache...lnk&cd=7&gl=de

    there are a lot more references out there.
    At least I saw it myself: I wondered for days why my scheduler printed just a bunch of crap as debug output. Switching to printf cured it

    Hm, but your link makes me wonder now...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. clock()
    By C_ntua in forum C Programming
    Replies: 19
    Last Post: 10-08-2008, 11:45 AM
  2. Determing the amount of change(money)
    By Kyeong in forum C Programming
    Replies: 11
    Last Post: 09-30-2008, 04:36 PM
  3. How to resume thread at the specific time instance?
    By qingxing2005 in forum Windows Programming
    Replies: 1
    Last Post: 01-21-2007, 12:28 AM
  4. Having a problem!
    By Zildjian in forum C++ Programming
    Replies: 6
    Last Post: 10-18-2004, 09:40 AM
  5. Multi-Thread Programming
    By drdroid in forum C++ Programming
    Replies: 6
    Last Post: 04-04-2002, 02:53 PM