Re: how to make a function thread safe?



On Fri, 2005-01-28 at 00:18, Felix Kater wrote:
Hi,

is a function thread save when all inside code is wrapped into a static
mutex?

By definition, no.

You should use mutual exclusion to access/change the variables used by
various threads.

What is with this function: Could a second thread influence the first
thread while it is looping (because of the pointer argument)?

The second thread will be unable to lock the mutex, meanwhile the first
one does not unlock it.

void f(gint* my_gint){

  static GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;

  g_static_mutex_lock(&my_mutex);

  while(TRUE)
  {
    
    g_printf("value: %d\n", *my_gint);

    /* ... */

  }

  g_static_mutex_unlock(&my_mutex);
}

This code will lock the mutex while you're in the "while(TRUE)" loop.

No other thread will be able to get the lock, so all other threads will
block idefinitely.


Regards.
-- 
Iago Rubio



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