Sign in to follow this  

two threads, one read?

This topic is 4202 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

say you have class thread, if I have two class threads' could one read the other with out fear of corruption? my concern is trying to read memory that might be being accessed by another thread. I know trying to write to memory which is reserved by another thread can be bad, but im not to sure about reading.

Share this post


Link to post
Share on other sites
Reading is fine. So is writing, to some extent. The problem occurs when thread A reads data, thread B writes data, then thread A reads more data, expecing the state to be as it was when it first read data.

For example, in a linked list, if you want to delete the last node, you do two steps:
  • Unlink the node (set the pointer of the 2nd last node to NULL)
  • Delete the last node
    Consider this: Thread A unlinks the node, then thread B gets scheduled in and starts traversing the list. Thread B is just about to access the last element (It reads the pointer, and starts to access data in the node or something), then gets scheduled out. Thread A gets scheduled back in, and deletes the last node, does some stuff then gets scheduled out. Thread B accesses the data it was trying to. Boom. The memory has been deleted. As far as thread B is concerned, it was fine a moment ago, but now it's not.

    To avoid situations like that, you want to use a critical section or mutex.

    Share this post


    Link to post
    Share on other sites
    As stated above, reading is fine.

    As for writing, do a search for lock-free data structures - lots of interesting research going on in this area.

    Share this post


    Link to post
    Share on other sites
    Quote:
    Original post by DGates
    As for writing, do a search for lock-free data structures - lots of interesting research going on in this area.
    Game Programming Gems 6 has a nice chapter on Lock Free Data Structures, including free lists, normal lists and queues.

    Share this post


    Link to post
    Share on other sites

    This topic is 4202 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

    If you intended to correct an error in the post then please contact us.

    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now

    Sign in to follow this