Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The rules are:</p> <p>1) Locks protect data and not code. When data is protected by a lock, code that accesses that data must acquire the data's lock.</p> <p>2) Locks should be acquired as late as possible and released as early as possible. This can include shifting work from inside the critical section to outside the critical section.</p> <p>3) Data that is only read (and not modified) doesn't need a lock. This includes things like <code>"Channel id [ %d ] ..."</code> format strings (which should be treated as constant).</p> <p>4) Data that can only be accessed by one thread doesn't need a lock. This includes things like function parameters and local variables.</p> <p>5) Finer grained locking is better than coarse grained locking. For example, rather than having one large data structure with one lock, often you can split that large data structure into many smaller structures with many locks.</p> <p>6) If any code needs more than one lock at a time, you need to define a "locking order". For example, if one thread acquires lock A then lock B, does some work then releases the locks; and if another thread acquires lock B then lock A, does some work then release the locks; then you can get deadlock (each thread has one lock but needs both to continue). Defining a "locking order" (e.g. saying that lock A must be acquired before lock B) prevents this sort of bug.</p> <p>For your code, the first few lines don't need a lock at all because they only access function parameters and local variables (rule 4). The data pointed to by <code>void *data</code> may or may not need a lock depending on what it is - e.g. if each thread has its own separate data (rule 4), or if that data is only read (rule 3), then no lock is needed. For the <code>LOG_INFO()</code> function no additional lock is needed (excluding the <code>void *data</code> lock if it exists) in the code you posted, but it may have its own internal lock (e.g. to protect a shared log).</p> <p>For an example of rule 2, if the <code>LOCK_INFO</code> takes a little while your code could do something like this to release the first lock earlier:</p> <pre><code>temp_ID = channel-&gt;id; temp_name = strdup(channel-&gt;name); // Should check for NULL! temp_delay = channel-&gt;delay_time; /* UNLOCK HERE */ LOG_INFO("Channel id [ %d ] Channel name [ %s ] Delay time [ %d ]", temp_ID, temp_name, temp_delay); free(temp_name); </code></pre> <p>Also note that if <code>LOCK_INFO()</code> uses a lock, releasing the first lock earlier will also help with rule 6.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload