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 void NSDestroyThreadHandle(NSThreadHandle *);
31 NSThreadHandle * NSThreadInit(NSThreadFunc func, void * data)
35 NS_LOG(ERROR, "thread function is null");
39 NSThreadHandle * handle = (NSThreadHandle *)OICMalloc(sizeof(NSThreadHandle));
42 NS_LOG(ERROR, "thread allocation fail");
46 memset(handle, 0, sizeof(NSThreadHandle));
48 pthread_mutexattr_init(&(handle->mutex_attr));
49 if (pthread_mutexattr_settype(&(handle->mutex_attr), PTHREAD_MUTEX_RECURSIVE))
51 NS_LOG(ERROR, "thread mutex_attr init fail");
52 NSDestroyThreadHandle(handle);
56 if (pthread_mutex_init(&(handle->mutex), &(handle->mutex_attr)))
58 NS_LOG(ERROR, "thread mutex init fail");
59 NSDestroyThreadHandle(handle);
63 if (pthread_mutex_lock(&(handle->mutex)))
65 NS_LOG(ERROR, "thread mutex lock fail");
66 NSDestroyThreadHandle(handle);
70 handle->isStarted = true;
72 if (pthread_create(&(handle->thread_id), NULL, func,
73 (data == NULL) ? (void *) handle : (void *)data))
75 NS_LOG(ERROR, "thread create fail");
76 NSDestroyThreadHandle(handle);
80 pthread_mutex_unlock(&(handle->mutex));
85 void NSThreadLock(NSThreadHandle * handle)
87 pthread_mutex_lock(&(handle->mutex));
90 void NSThreadUnlock(NSThreadHandle * handle)
92 pthread_mutex_unlock(&(handle->mutex));
95 void NSThreadStop(NSThreadHandle * handle)
97 NSDestroyThreadHandle(handle);
100 void NSDestroyThreadHandle(NSThreadHandle * handle)
102 handle->isStarted = false;
104 if (handle->thread_id)
106 pthread_join(handle->thread_id, NULL);
109 pthread_mutex_destroy(&(handle->mutex));
110 pthread_mutexattr_destroy(&(handle->mutex_attr));