Re: GThread and GCond



Fernando Apesteguía wrote:
Hi,

I hope you can help me ;)

I'm working with two threads. One of them is running in an infinite loop
(well, it finishes under certain conditions)
What I want to do is that the infinite loop pauses some times. So I create a
GCond, but I think I didn't understand how it works.
I do something like this:

Thread 1:

for (;;){
  g_mutex_lock(my_mutex);
  g_cond_wait(my_cond,mi_mutex);
  do_some_work_here....
  g_mutex_unlock(mi_mutex);
}

The Thread 2 asynchronously toggles the value of a variable between 0 and 1.
When the value is 1, I want the loop runs continuously, but when it is 0,
the loop stops.

if (value==0){
        value=1;
        g_cond_signal(my_cond);
    }
    else
        value=0;

I've read this:
http://developer.gnome.org/doc/API/2.0/glib/glib-Threads.html#g-thread-create
"The GCond<http://developer.gnome.org/doc/API/2.0/glib/glib-Threads.html#GCond>struct
is an opaque data structure to represent a condition"

So, the GCond represents the condition, and are not the condition itself...
So when I use g_cond_signal I think I'm telling "the condition is true,
unlock". But in the next iteration, the loop locks again.

How can I tell "The condition is STILL true..."?

The condition is just a thing you can wait on untill its signalled,
thats all... there is no relation between your 'value' variable
and the condition.

in this small example; the musicplayer frontend pauses the worker
thread (that usually loops in a read/write loop):

Player worker thread:
====================

/* This code is at the beginning of the loop (before writing
 * the next chunk of song data
 */
mp_mutex_lock(mp->paused_mutex);
while (mp->paused) {
     g_cond_wait(mp->paused_cond, mp->paused_mutex);
}
mp_mutex_unlock(mp->paused_mutex);


Musicplayer frontend thread:
===========================

To pause the player thread:
    mp->paused = TRUE;

To unpause the player thread:
    mp->paused = FALSE;
    g_cond_signal (mp->paused_cond);

Cheers,
                          -Tristan



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]