+}
+
+/****************************** SILC Cond API *******************************/
+
+/* SILC Conditional Variable context */
+struct SilcCondStruct {
+#ifdef SILC_THREADS
+ pthread_cond_t cond;
+#else
+ void *tmp;
+#endif /* SILC_THREADS*/
+};
+
+SilcBool silc_cond_alloc(SilcCond *cond)
+{
+#ifdef SILC_THREADS
+ *cond = silc_calloc(1, sizeof(**cond));
+ if (*cond == NULL)
+ return FALSE;
+ if (pthread_cond_init(&(*cond)->cond, NULL)) {
+ silc_set_errno_posix(errno);
+ silc_free(*cond);
+ return FALSE;
+ }
+ return TRUE;
+#else
+ return FALSE;
+#endif /* SILC_THREADS*/
+}
+
+void silc_cond_free(SilcCond cond)
+{
+#ifdef SILC_THREADS
+ pthread_cond_destroy(&cond->cond);
+ silc_free(cond);
+#endif /* SILC_THREADS*/
+}
+
+void silc_cond_signal(SilcCond cond)
+{
+#ifdef SILC_THREADS
+ pthread_cond_signal(&cond->cond);
+#endif /* SILC_THREADS*/
+}
+
+void silc_cond_broadcast(SilcCond cond)
+{
+#ifdef SILC_THREADS
+ pthread_cond_broadcast(&cond->cond);
+#endif /* SILC_THREADS*/
+}
+
+void silc_cond_wait(SilcCond cond, SilcMutex mutex)
+{
+#ifdef SILC_THREADS
+ pthread_cond_wait(&cond->cond, &mutex->mutex);
+#endif /* SILC_THREADS*/
+}
+
+SilcBool silc_cond_timedwait(SilcCond cond, SilcMutex mutex,
+ int timeout)
+{
+#ifdef SILC_THREADS
+ struct timespec t;
+ if (timeout) {
+ t.tv_sec = timeout / 1000;
+ t.tv_nsec = (timeout % 1000) * 1000;
+ return pthread_cond_timedwait(&cond->cond, &mutex->mutex, &t) == 0;
+ }
+
+ return pthread_cond_wait(&cond->cond, &mutex->mutex) == 0;
+#else
+ return FALSE;
+#endif /* SILC_THREADS*/
+}
+
+/************************** Thread-local Storage ****************************/
+
+#if (defined(SILC_THREADS) && defined(HAVE_PTHREAD_KEY_CREATE) && \
+ defined(HAVE_PTHREAD_ONCE))
+
+static pthread_key_t key;
+static pthread_once_t key_once = PTHREAD_ONCE_INIT;
+
+static void silc_thread_tls_destructor(void *context)
+{
+ silc_free(context);
+}
+
+static void silc_thread_tls_alloc(void)
+{
+ if (pthread_key_create(&key, silc_thread_tls_destructor))
+ SILC_LOG_ERROR(("Error creating Thread-local storage"));
+}
+
+SilcTls silc_thread_tls_init(void)
+{
+ SilcTls tls;
+
+ pthread_once(&key_once, silc_thread_tls_alloc);
+
+ if (silc_thread_get_tls())
+ return silc_thread_get_tls();
+
+ /* Allocate Tls for the thread */
+ tls = silc_calloc(1, sizeof(*tls));
+ if (!tls) {
+ SILC_LOG_ERROR(("Error allocating Thread-local storage"));
+ return NULL;
+ }
+
+ pthread_setspecific(key, tls);
+ return tls;
+}
+
+SilcTls silc_thread_get_tls(void)
+{
+ return pthread_getspecific(key);
+}
+
+#else
+
+SilcTlsStruct tls;
+SilcTls tls_ptr = NULL;
+
+SilcTls silc_thread_tls_init(void)
+{
+ if (silc_thread_get_tls())
+ return silc_thread_get_tls();
+
+ tls_ptr = &tls;
+ memset(tls_ptr, 0, sizeof(*tls_ptr));
+ return tls_ptr;
+}
+
+SilcTls silc_thread_get_tls(void)
+{
+ return tls_ptr;
+}
+
+#endif