Thread: threads and synchronization

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105

    threads and synchronization

    Hi everyone.

    Let's say I am to make my own mutex, lets call it lock / unlock.
    Then have the following code:
    (And please, this is only a very c-looking pseudo-code. Don't bother saying how the code is or what the point of it is. Its just an example in pseudo-code. No smart ass comments, please.)
    Code:
    struct lock_l l; // Lock
    int global; // Global
    
    thread1() {
    
      // Do some local non-essential work
    
      // Enter mutex
      lock(&l);
      global = 0;
      unlock(&l);
    
      // Do some local non essential work.
    }
    
    thread2() {
      lock(&l); 
      // Do something with global
      unlock(&l);
    }

    So, thread 1 just sets global to 0.
    Thread 2 do some very important calculation on this variable.

    Now , what prevents the compiler-optimizer from changing thread1 to this, moving global = 0; outside the lock. :
    Code:
    thread1() {
      global = 0;
      // Enter mutex
      lock(&l);
      unlock(&l);
    }
    Is this what memory barriers instructions are for? Or this those only for hardware reordering?
    How can I be 100% sure the opitimizer will NOT move statements in between my 2 self made mutex-functions, outside them?
    Last edited by Drogin; 09-26-2010 at 08:00 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help: Multi-threading and Synchronization
    By Anom in forum C Programming
    Replies: 7
    Last Post: 12-08-2009, 05:34 PM
  2. Synchronization Question
    By CyrexCore2k in forum C Programming
    Replies: 4
    Last Post: 05-01-2008, 02:51 AM
  3. using this as synchronization object
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 03-22-2008, 07:49 AM
  4. Replies: 0
    Last Post: 10-06-2007, 01:25 PM
  5. Thread synchronization Assignment help!!
    By rossi143 in forum C Programming
    Replies: 2
    Last Post: 03-25-2007, 07:07 AM