Re: pthread help
- From: Måns Rullgård <mru@xxxxxxxxxxxxx>
- Date: Sat, 11 Nov 2006 14:13:36 +0000
"David Schwartz" <davids@xxxxxxxxxxxxx> writes:
void thread_fun(void)
{
for (;;) {
if (flag) {
.....output .....
}
}
You need to hold a mutex while you test the flag.
Why? If the body of the if statement doesn't depend on 'flag' not
changing while it's executing, there's no need for locking. If it
does need 'flag' to stay constant, the lock must be held for the
entire time, not just while testing it. Assuming of course that
accessing 'flag' is atomic.
void run (void)
{
pthread_mutex_lock(&m);
flag=1;
pthread_mutex_unlock(&m);
}
void pause (void)
{
pthread_mutex_lock(&m);
flag=0;
pthread_mutex_unlock(&m);
}
Again, no need for locking if 'flag' is written atomically and the
code that reads 'flag' doesn't need it to remain constant over some
period of time.
Accessing shared data doesn't always need locking. Overzealous
locking is what makes some threaded applications slow, even on
multi-CPU machines. Figuring out exactly when to lock is the
difficult part of multithreaded programming. Designing the
application in a way that needs minimal locking can also be a
challenge.
--
Måns Rullgård
mru@xxxxxxxxxxxxx
.
- Follow-Ups:
- Re: pthread help
- From: David Schwartz
- Re: pthread help
- References:
- pthread help
- From: gaetanoortisi
- Re: pthread help
- From: David Schwartz
- Re: pthread help
- From: gaetanoortisi
- Re: pthread help
- From: David Schwartz
- pthread help
- Prev by Date: CK-ERP (Open Source ERP / CRM / MRP) v.0.21.1 released
- Next by Date: Unix Scripting Education Survey
- Previous by thread: Re: pthread help
- Next by thread: Re: pthread help
- Index(es):
Relevant Pages
|