/*
 * Copyright (c) 2002-2005 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: thr-1.c,v 1.6 2006/02/16 19:19:40 ca Exp $")
#include "sm/assert.h"
#include "sm/error.h"
#include "sm/str.h"
#include "sm/test.h"
#include "sm/io.h"
#include "sm/ctype.h"

#include "st.h"
#include "common.h"	/* HACK for debugging, otherwise structs are hidden */

#include <stdio.h>

st_cond_t	cond1;
st_mutex_t	mutex1;
int Verbose = 0;
int shared;

/* ARGSUSED0 */
static void *
wait1(void *arg)
{
	int r;
	st_utime_t timeout;

	(void) arg;
	timeout = 1000000;
	if (Verbose > 0)
		fprintf(stderr, "wait1: timeout=%ld\n", (long) timeout);
	r = st_cond_timedwait(cond1, timeout);
	SM_TEST(r == 0);
	if (r == 0)
	{
		r = st_mutex_lock(mutex1);
		SM_TEST(r == 0);
		if (r != 0)
			return NULL;
		SM_TEST(shared == 1);
		shared = 4;
		r = st_mutex_unlock(mutex1);
		SM_TEST(r == 0);
	}
	else if (r == -1)
	{
		if (ETIME == errno)
			fprintf(stderr, "st_cond_timedwait timeout\n");
		else
			perror("st_cond_timedwait");
	}
	if (Verbose > 1)
		printf("wait1: r=%d\n", r);
	return NULL;
}


int
main(int argc, char *argv[])
{
	int r;
	st_thread_t thr1;
	void *rv;
	st_utime_t timeout;

	timeout = 1000;

	sm_test_begin(argc, argv, "test st_cond");

	/* Initialize the ST library */
	r = st_init();
	SM_TEST(r >= 0);
	if (r < 0)
	{
		perror("st_init");
		exit(1);
	}
	cond1 = st_cond_new();
	SM_TEST(cond1 != NULL);
	if (NULL == cond1)
	{
		perror("st_cond_new");
		exit(1);
	}
	mutex1 = st_mutex_new();
	SM_TEST(mutex1 != NULL);
	if (NULL == mutex1)
	{
		perror("st_mutex_new");
		exit(1);
	}
	r = st_mutex_lock(mutex1);
	SM_TEST(r == 0);
	if (r != 0)
		goto cdest;
	shared = 1;

	thr1 = st_thread_create(wait1, (void *) 0, 1, 0);
	SM_TEST(thr1 != NULL);
	if (NULL == thr1)
	{
		perror("st_thread_create");
		exit(1);
	}
	SM_TEST(shared == 1);

	r = st_mutex_unlock(mutex1);
	SM_TEST(r == 0);
	if (r != 0)
		goto join;

	if (Verbose > 1)
		fprintf(stderr, "main: sleep\n");
	r = st_usleep(timeout);
	SM_TEST(r != -1);
	if (r == -1)
	{
		perror("st_usleep");
		exit(1);
	}
	if (Verbose > 1)
		fprintf(stderr, "main: signal\n");
	r = st_cond_signal(cond1);
	SM_TEST(r == 0);
	if (Verbose > 1)
		fprintf(stderr, "main: join\n");

  join:
	r = st_thread_join(thr1, &rv);
	SM_TEST(r == 0);
	if (Verbose > 1)
		printf("join: r=%d\n", r);
	SM_TEST(shared == 4);

  cdest:
	r = st_cond_destroy(cond1);
	SM_TEST(r == 0);
	if (r != 0)
	{
		perror("st_cond_destroy");
		exit(1);
	}
	r = st_mutex_destroy(mutex1);
	SM_TEST(r == 0);
	if (r != 0)
	{
		perror("st_mutex_destroy");
		exit(1);
	}

	return sm_test_end();
}


syntax highlighted by Code2HTML, v. 0.9.1