Thread: locking actions to special threads

  1. #1
    Registered User
    Join Date
    Nov 2006

    locking actions to special threads


    imagine some complex control system, input -> logic -> output. inputs can be (at least virtually) be given in parallel and have to be executed in parallel. so one end up with lot of different threads, maybe each responsible for a special task.
    The design of the system expects that some data is changed / functions are called only by a special thread.
    Is there any approved way of ensuring that, beside just to document it inside the code (
    // call this only from thread foo, else everything breaks

    Thank you in advance!

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Thread API's usually have a concept of "thread ID" and function to get the current thread's ID. So you could setup some logic to ensure "only thread ID X should be calling this function".

    Although I would question the overall design if this kind of constraint really needs to be checked in a non-debug build.


  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    I agree with Codeplug, this should only (if at all) be checked in a debug build.

    If we assume that it is an object that is only supposed to ever be used by its creating thread, one way would be to do a "getthreadid" at construction time and store that as part of the object, and then when the object is accessed later (at some strategic point), check that the current thread is the same as the constructing thread.

    Another option, that is a bit quicker but also a little bit less reliable (particularly if threads are created and destroyed during the processing, rather than created at startup and destroyed when the app finishes) would be to store the address of a constructor local variable, and check that this value is within a reasonable distance of the address of a local variable in the checker (less than the stack-size of the thread, for sure).

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 10-17-2008, 11:28 AM
  2. Yet another n00b in pthreads ...
    By dimis in forum C++ Programming
    Replies: 14
    Last Post: 04-07-2008, 12:43 AM
  3. Classes and Threads
    By Halloko in forum Windows Programming
    Replies: 9
    Last Post: 10-23-2005, 05:27 AM
  4. problem with win32 threads
    By pdmarshall in forum C++ Programming
    Replies: 6
    Last Post: 07-29-2004, 02:39 PM
  5. Block and wake up certain threads
    By Spark in forum C Programming
    Replies: 9
    Last Post: 06-01-2002, 03:39 AM