osSemaphore.c 11.3 KB
Newer Older
S
slguan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#define _DEFAULT_SOURCE
#include "os.h"
S
Shengliang Guan 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

#if defined(_TD_WINDOWS_64) || defined(_TD_WINDOWS_32)

/*
 * windows implementation
 */

#include <windows.h>

bool taosCheckPthreadValid(pthread_t thread) { return thread.p != NULL; }

void taosResetPthread(pthread_t* thread) { thread->p = 0; }

int64_t taosGetPthreadId(pthread_t thread) {
#ifdef PTW32_VERSION
  return pthread_getw32threadid_np(thread);
#else
  return (int64_t)thread;
#endif
}

int64_t taosGetSelfPthreadId() { return GetCurrentThreadId(); }

bool taosComparePthread(pthread_t first, pthread_t second) { return first.p == second.p; }

int32_t taosGetPId() { return GetCurrentProcessId(); }

45
int32_t taosGetAppName(char* name, int32_t* len) {
S
Shengliang Guan 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  char filepath[1024] = {0};

  GetModuleFileName(NULL, filepath, MAX_PATH);
  char* sub = strrchr(filepath, '.');
  if (sub != NULL) {
    *sub = '\0';
  }
  strcpy(name, filepath);

  if (len != NULL) {
    *len = (int32_t)strlen(filepath);
  }

  return 0;
}

int32_t tsem_wait(tsem_t* sem) {
  int ret = 0;
  do {
    ret = sem_wait(sem);
  } while (ret != 0 && errno == EINTR);
  return ret;
}

#elif defined(_TD_DARWIN_64)

/*
 * darwin implementation
 */

F
freemine 已提交
76 77
#include <libproc.h>

78 79 80 81 82 83
// #define SEM_USE_PTHREAD
// #define SEM_USE_POSIX
#define SEM_USE_SEM

#ifdef SEM_USE_SEM
#include <mach/mach_error.h>
S
Shengliang Guan 已提交
84
#include <mach/mach_init.h>
85 86
#include <mach/semaphore.h>
#include <mach/task.h>
87
#include <pthread.h>
88

S
Shengliang Guan 已提交
89 90 91 92 93
static pthread_t      sem_thread;
static pthread_once_t sem_once;
static task_t         sem_port;
static volatile int   sem_inited = 0;
static semaphore_t    sem_exit;
94

S
Shengliang Guan 已提交
95
static void *sem_thread_routine(void *arg) {
96
  (void)arg;
97 98
  setThreadName("sem_thrd");

99 100 101 102 103 104 105 106 107 108 109 110 111
  sem_port = mach_task_self();
  kern_return_t ret = semaphore_create(sem_port, &sem_exit, SYNC_POLICY_FIFO, 0);
  if (ret != KERN_SUCCESS) {
    fprintf(stderr, "==%s[%d]%s()==failed to create sem_exit\n", basename(__FILE__), __LINE__, __func__);
    sem_inited = -1;
    return NULL;
  }
  sem_inited = 1;
  semaphore_wait(sem_exit);
  return NULL;
}

static void once_init(void) {
S
TD-4088  
Shengliang Guan 已提交
112
  int r = 0;
113 114 115 116 117
  r = pthread_create(&sem_thread, NULL, sem_thread_routine, NULL);
  if (r) {
    fprintf(stderr, "==%s[%d]%s()==failed to create thread\n", basename(__FILE__), __LINE__, __func__);
    return;
  }
S
Shengliang Guan 已提交
118
  while (sem_inited == 0) {
119 120 121 122 123
    ;
  }
}
#endif

F
freemine 已提交
124
struct tsem_s {
125
#ifdef SEM_USE_PTHREAD
S
Shengliang Guan 已提交
126 127 128
  pthread_mutex_t  lock;
  pthread_cond_t   cond;
  volatile int64_t val;
129
#elif defined(SEM_USE_POSIX)
S
Shengliang Guan 已提交
130 131
  size_t        id;
  sem_t *       sem;
132
#elif defined(SEM_USE_SEM)
S
Shengliang Guan 已提交
133 134 135 136
  semaphore_t sem;
#else   // SEM_USE_PTHREAD
  dispatch_semaphore_t sem;
#endif  // SEM_USE_PTHREAD
137

S
Shengliang Guan 已提交
138
  volatile unsigned int valid : 1;
F
freemine 已提交
139 140
};

S
TD-4088  
Shengliang Guan 已提交
141
int tsem_init(tsem_t *sem, int pshared, unsigned int value) {
142
  // fprintf(stderr, "==%s[%d]%s():[%p]==creating\n", basename(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
143 144 145
  if (*sem) {
    fprintf(stderr, "==%s[%d]%s():[%p]==already initialized\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
S
slguan 已提交
146
  }
S
Shengliang Guan 已提交
147
  struct tsem_s *p = (struct tsem_s *)calloc(1, sizeof(*p));
F
freemine 已提交
148 149 150 151 152
  if (!p) {
    fprintf(stderr, "==%s[%d]%s():[%p]==out of memory\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }

153
#ifdef SEM_USE_PTHREAD
S
TD-4088  
Shengliang Guan 已提交
154
  int r = pthread_mutex_init(&p->lock, NULL);
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
  do {
    if (r) break;
    r = pthread_cond_init(&p->cond, NULL);
    if (r) {
      pthread_mutex_destroy(&p->lock);
      break;
    }
    p->val = value;
  } while (0);
  if (r) {
    fprintf(stderr, "==%s[%d]%s():[%p]==not created\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
#elif defined(SEM_USE_POSIX)
  static size_t tick = 0;
  do {
    size_t id = atomic_add_fetch_64(&tick, 1);
S
Shengliang Guan 已提交
172
    if (id == SEM_VALUE_MAX) {
173 174 175
      atomic_store_64(&tick, 0);
      id = 0;
    }
S
Shengliang Guan 已提交
176
    char name[NAME_MAX - 4];
177
    snprintf(name, sizeof(name), "/t%ld", id);
S
Shengliang Guan 已提交
178 179 180
    p->sem = sem_open(name, O_CREAT | O_EXCL, pshared, value);
    p->id = id;
    if (p->sem != SEM_FAILED) break;
S
TD-4088  
Shengliang Guan 已提交
181
    int e = errno;
S
Shengliang Guan 已提交
182 183 184 185
    if (e == EEXIST) continue;
    if (e == EINTR) continue;
    fprintf(stderr, "==%s[%d]%s():[%p]==not created[%d]%s\n", basename(__FILE__), __LINE__, __func__, sem, e,
            strerror(e));
186
    abort();
S
Shengliang Guan 已提交
187
  } while (p->sem == SEM_FAILED);
188 189
#elif defined(SEM_USE_SEM)
  pthread_once(&sem_once, once_init);
S
Shengliang Guan 已提交
190
  if (sem_inited != 1) {
191 192 193 194
    fprintf(stderr, "==%s[%d]%s():[%p]==internal resource init failed\n", basename(__FILE__), __LINE__, __func__, sem);
    errno = ENOMEM;
    return -1;
  }
F
freemine 已提交
195
  kern_return_t ret = semaphore_create(sem_port, &p->sem, SYNC_POLICY_FIFO, value);
196 197 198 199 200
  if (ret != KERN_SUCCESS) {
    fprintf(stderr, "==%s[%d]%s():[%p]==semophore_create failed\n", basename(__FILE__), __LINE__, __func__, sem);
    // we fail-fast here, because we have less-doc about semaphore_create for the moment
    abort();
  }
S
Shengliang Guan 已提交
201
#else   // SEM_USE_PTHREAD
F
freemine 已提交
202 203 204 205 206
  p->sem = dispatch_semaphore_create(value);
  if (p->sem == NULL) {
    fprintf(stderr, "==%s[%d]%s():[%p]==not created\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
S
Shengliang Guan 已提交
207
#endif  // SEM_USE_PTHREAD
208

F
freemine 已提交
209 210 211
  p->valid = 1;

  *sem = p;
S
slguan 已提交
212 213 214 215

  return 0;
}

S
TD-4088  
Shengliang Guan 已提交
216
int tsem_wait(tsem_t *sem) {
F
freemine 已提交
217 218 219 220 221 222 223 224 225
  if (!*sem) {
    fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
    fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
#ifdef SEM_USE_PTHREAD
  if (pthread_mutex_lock(&p->lock)) {
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  p->val -= 1;
  if (p->val < 0) {
    if (pthread_cond_wait(&p->cond, &p->lock)) {
      fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
      abort();
    }
  }
  if (pthread_mutex_unlock(&p->lock)) {
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  return 0;
#elif defined(SEM_USE_POSIX)
  return sem_wait(p->sem);
#elif defined(SEM_USE_SEM)
  return semaphore_wait(p->sem);
S
Shengliang Guan 已提交
247
#else   // SEM_USE_PTHREAD
F
freemine 已提交
248
  return dispatch_semaphore_wait(p->sem, DISPATCH_TIME_FOREVER);
S
Shengliang Guan 已提交
249
#endif  // SEM_USE_PTHREAD
S
slguan 已提交
250 251
}

S
TD-4088  
Shengliang Guan 已提交
252
int tsem_post(tsem_t *sem) {
F
freemine 已提交
253 254 255 256 257 258 259 260 261
  if (!*sem) {
    fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
    fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
#ifdef SEM_USE_PTHREAD
  if (pthread_mutex_lock(&p->lock)) {
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  p->val += 1;
  if (p->val <= 0) {
    if (pthread_cond_signal(&p->cond)) {
      fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
      abort();
    }
  }
  if (pthread_mutex_unlock(&p->lock)) {
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  return 0;
#elif defined(SEM_USE_POSIX)
  return sem_post(p->sem);
#elif defined(SEM_USE_SEM)
  return semaphore_signal(p->sem);
S
Shengliang Guan 已提交
283
#else   // SEM_USE_PTHREAD
F
freemine 已提交
284
  return dispatch_semaphore_signal(p->sem);
S
Shengliang Guan 已提交
285
#endif  // SEM_USE_PTHREAD
F
freemine 已提交
286 287
}

S
TD-4088  
Shengliang Guan 已提交
288
int tsem_destroy(tsem_t *sem) {
289
  // fprintf(stderr, "==%s[%d]%s():[%p]==destroying\n", basename(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
290
  if (!*sem) {
291 292
    // fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", basename(__FILE__), __LINE__, __func__, sem);
    // abort();
F
freemine 已提交
293 294 295 296
    return 0;
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    // fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", basename(__FILE__), __LINE__, __func__, sem);
    // abort();
    return 0;
  }
#ifdef SEM_USE_PTHREAD
  if (pthread_mutex_lock(&p->lock)) {
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  p->valid = 0;
  if (pthread_cond_destroy(&p->cond)) {
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  if (pthread_mutex_unlock(&p->lock)) {
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
  if (pthread_mutex_destroy(&p->lock)) {
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", basename(__FILE__), __LINE__, __func__, sem);
    abort();
  }
#elif defined(SEM_USE_POSIX)
S
Shengliang Guan 已提交
320
  char name[NAME_MAX - 4];
321
  snprintf(name, sizeof(name), "/t%ld", p->id);
S
TD-4088  
Shengliang Guan 已提交
322
  int r = sem_unlink(name);
323
  if (r) {
S
TD-4088  
Shengliang Guan 已提交
324
    int e = errno;
S
Shengliang Guan 已提交
325 326
    fprintf(stderr, "==%s[%d]%s():[%p]==unlink failed[%d]%s\n", basename(__FILE__), __LINE__, __func__, sem, e,
            strerror(e));
F
freemine 已提交
327 328
    abort();
  }
329 330
#elif defined(SEM_USE_SEM)
  semaphore_destroy(sem_port, p->sem);
S
Shengliang Guan 已提交
331 332
#else   // SEM_USE_PTHREAD
#endif  // SEM_USE_PTHREAD
F
freemine 已提交
333 334 335 336 337

  p->valid = 0;
  free(p);

  *sem = NULL;
S
slguan 已提交
338 339
  return 0;
}
F
freemine 已提交
340

F
freemine 已提交
341 342
bool taosCheckPthreadValid(pthread_t thread) {
  uint64_t id = 0;
S
Shengliang Guan 已提交
343
  int      r = pthread_threadid_np(thread, &id);
F
freemine 已提交
344 345 346 347
  return r ? false : true;
}

int64_t taosGetSelfPthreadId() {
348 349
  uint64_t id;
  pthread_threadid_np(0, &id);
S
Shengliang Guan 已提交
350
  return (int64_t)id;
F
freemine 已提交
351 352
}

S
Shengliang Guan 已提交
353
int64_t taosGetPthreadId(pthread_t thread) { return (int64_t)thread; }
F
freemine 已提交
354

S
Shengliang Guan 已提交
355
void taosResetPthread(pthread_t *thread) { *thread = NULL; }
F
freemine 已提交
356

S
Shengliang Guan 已提交
357
bool taosComparePthread(pthread_t first, pthread_t second) { return pthread_equal(first, second) ? true : false; }
F
freemine 已提交
358

S
Shengliang Guan 已提交
359
int32_t taosGetPId() { return (int32_t)getpid(); }
F
freemine 已提交
360

361
int32_t taosGetAppName(char *name, int32_t *len) {
S
Shengliang Guan 已提交
362
  char buf[PATH_MAX + 1];
F
freemine 已提交
363
  buf[0] = '\0';
S
Shengliang Guan 已提交
364
  proc_name(getpid(), buf, sizeof(buf) - 1);
F
freemine 已提交
365 366 367 368 369 370 371
  buf[PATH_MAX] = '\0';
  size_t n = strlen(buf);
  if (len) *len = n;
  if (name) strcpy(name, buf);
  return 0;
}

S
Shengliang Guan 已提交
372 373 374 375 376 377 378
#else

/*
 * linux implementation
 */

#include <sys/syscall.h>
S
Shengliang Guan 已提交
379
#include <unistd.h>
S
Shengliang Guan 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

bool taosCheckPthreadValid(pthread_t thread) { return thread != 0; }

int64_t taosGetSelfPthreadId() {
  static __thread int id = 0;
  if (id != 0) return id;
  id = syscall(SYS_gettid);
  return id;
}

int64_t taosGetPthreadId(pthread_t thread) { return (int64_t)thread; }
void    taosResetPthread(pthread_t* thread) { *thread = 0; }
bool    taosComparePthread(pthread_t first, pthread_t second) { return first == second; }
int32_t taosGetPId() { return getpid(); }

395
int32_t taosGetAppName(char* name, int32_t* len) {
S
Shengliang Guan 已提交
396 397
  const char* self = "/proc/self/exe";
  char        path[PATH_MAX] = {0};
F
freemine 已提交
398

S
Shengliang Guan 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
  if (readlink(self, path, PATH_MAX) <= 0) {
    return -1;
  }

  path[PATH_MAX - 1] = 0;
  char* end = strrchr(path, '/');
  if (end == NULL) {
    return -1;
  }

  ++end;

  strcpy(name, end);

  if (len != NULL) {
    *len = strlen(name);
  }

  return 0;
}

int32_t tsem_wait(tsem_t* sem) {
  int ret = 0;
  do {
    ret = sem_wait(sem);
  } while (ret != 0 && errno == EINTR);
  return ret;
}

#endif