two threads, one read?

Started by
3 comments, last by pcxmac 17 years, 10 months ago
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.
sig
Advertisement
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.
  • 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.
    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.
    cool, thanks, ill check out the lock-free data structures.
    sig

    This topic is closed to new replies.

    Advertisement