/* Create a mutex and a background thread, then set the fg and bg threads competing for the lock */

#include <glib.h>
#include <stdio.h>

#define STACK_SIZE 0x200000

gboolean running = FALSE;
GMutex *mutex;

static gpointer
bg_thread (void *data)
{
	running = TRUE;
	while (running) {
		fprintf (stderr, "<");
		fflush (stderr);
		g_mutex_lock (mutex);
		fprintf (stderr, "(");
		fflush (stderr);
		
		g_usleep (1000000 / 25);
		
		fprintf (stderr, ")");
		fflush (stderr);
		g_mutex_unlock (mutex);
		fprintf (stderr, ">");
		fflush (stderr);
	}
	return NULL;
}


int main()
{
	gint i = 0;

	if (!g_thread_supported ()) g_thread_init (NULL);
	
	mutex = g_mutex_new();

	g_print ("Starting background thread\n");
	g_thread_create_full ((GThreadFunc) bg_thread, NULL, 
		STACK_SIZE, FALSE, TRUE, G_THREAD_PRIORITY_NORMAL, NULL);

	for (i = 0; i < 100; i++) {
		fprintf (stderr, "{");
		fflush (stderr);
		g_mutex_lock (mutex);
		fprintf (stderr, "[");
		fflush (stderr);

		g_usleep (1000000 / 20);
		
		fprintf (stderr, "]");
		fflush (stderr);
		g_mutex_unlock (mutex);
		fprintf (stderr, "}");
		fflush (stderr);

		g_usleep (1000000 / 5);
	}
	
	running = FALSE;
	return 0;
}


