1 //******************************************************************
3 // Copyright 2016 Samsung Electronics All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 #include "NSConstants.h"
24 #include "NSConsumerCommon.h"
27 #include "oic_malloc.h"
29 static pthread_mutex_t g_create_mutex;
31 NSConsumerThread * NSThreadInit(NSThreadFunc func, void * data)
33 NS_VERIFY_NOT_NULL(func, NULL);
35 pthread_mutex_init(&g_create_mutex, NULL);
37 NSConsumerThread * handle = (NSConsumerThread *)OICMalloc(sizeof(NSConsumerThread));
38 NS_VERIFY_NOT_NULL(handle, NULL);
40 memset(handle, 0, sizeof(NSConsumerThread));
42 pthread_mutexattr_init(&(handle->mutex_attr));
44 int pthreadResult = pthread_mutexattr_settype(&(handle->mutex_attr), PTHREAD_MUTEX_RECURSIVE);
45 NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(pthreadResult == 0 ? (void *)1 : NULL,
46 NULL, NSDestroyThreadHandle(handle));
48 pthreadResult = pthread_mutex_init(&(handle->mutex), &(handle->mutex_attr));
49 NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(pthreadResult == 0 ? (void *)1 : NULL,
50 NULL, NSDestroyThreadHandle(handle));
52 pthread_mutex_lock(&g_create_mutex);
54 handle->isStarted = true;
56 pthreadResult = pthread_create(&(handle->thread_id), NULL, func,
57 (data == NULL) ? (void *) handle : (void *)data);
58 NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(pthreadResult == 0 ? (void *)1 : NULL,
59 NULL, NSDestroyThreadHandle(handle));
61 pthread_mutex_unlock(&g_create_mutex);
66 void NSThreadLock(NSConsumerThread * handle)
68 NS_VERIFY_NOT_NULL_V(handle);
70 pthread_mutex_lock(&(handle->mutex));
73 void NSThreadUnlock(NSConsumerThread * handle)
75 NS_VERIFY_NOT_NULL_V(handle);
77 pthread_mutex_unlock(&(handle->mutex));
80 void NSThreadStop(NSConsumerThread * handle)
82 NS_VERIFY_NOT_NULL_V(handle);
84 handle->isStarted = false;
87 NSDestroyThreadHandle(handle);
90 void NSThreadJoin(NSConsumerThread * handle)
92 NS_VERIFY_NOT_NULL_V(handle);
94 if (handle->thread_id)
96 pthread_join(handle->thread_id, NULL);
100 void NSDestroyThreadHandle(NSConsumerThread * handle)
102 NS_VERIFY_NOT_NULL_V(handle);
104 pthread_mutex_destroy(&(handle->mutex));
105 pthread_mutexattr_destroy(&(handle->mutex_attr));
109 pthread_mutex_unlock(&g_create_mutex);
112 void NSThreadDetach()
114 pthread_detach(pthread_self());