osSemaphore.c 12.1 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

wafwerar's avatar
wafwerar 已提交
19
#ifdef WINDOWS
S
Shengliang Guan 已提交
20 21 22 23 24 25 26

/*
 * windows implementation
 */

#include <windows.h>

wafwerar's avatar
wafwerar 已提交
27
bool taosCheckPthreadValid(TdThread thread) { return thread.p != NULL; }
S
Shengliang Guan 已提交
28

wafwerar's avatar
wafwerar 已提交
29
void taosResetPthread(TdThread* thread) { thread->p = 0; }
S
Shengliang Guan 已提交
30

wafwerar's avatar
wafwerar 已提交
31
int64_t taosGetPthreadId(TdThread thread) {
S
Shengliang Guan 已提交
32 33 34 35 36 37 38 39 40
#ifdef PTW32_VERSION
  return pthread_getw32threadid_np(thread);
#else
  return (int64_t)thread;
#endif
}

int64_t taosGetSelfPthreadId() { return GetCurrentThreadId(); }

wafwerar's avatar
wafwerar 已提交
41
bool taosComparePthread(TdThread first, TdThread second) { return first.p == second.p; }
S
Shengliang Guan 已提交
42 43 44

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
  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;
}

wafwerar's avatar
wafwerar 已提交
70 71 72 73 74 75
int32_t tsem_timewait(tsem_t* sem, int64_t nanosecs) {
  int ret = 0;

  return ret;
}

S
Shengliang Guan 已提交
76 77 78 79 80 81
#elif defined(_TD_DARWIN_64)

/*
 * darwin implementation
 */

F
freemine 已提交
82 83
#include <libproc.h>

84 85 86 87 88 89
// #define SEM_USE_PTHREAD
// #define SEM_USE_POSIX
#define SEM_USE_SEM

#ifdef SEM_USE_SEM
#include <mach/mach_error.h>
S
Shengliang Guan 已提交
90
#include <mach/mach_init.h>
91 92 93
#include <mach/semaphore.h>
#include <mach/task.h>

L
Liu Jicong 已提交
94
static TdThread     sem_thread;
wafwerar's avatar
wafwerar 已提交
95
static TdThreadOnce sem_once;
L
Liu Jicong 已提交
96 97 98
static task_t       sem_port;
static volatile int sem_inited = 0;
static semaphore_t  sem_exit;
99

S
Shengliang Guan 已提交
100
static void *sem_thread_routine(void *arg) {
101
  (void)arg;
102 103
  setThreadName("sem_thrd");

104 105 106
  sem_port = mach_task_self();
  kern_return_t ret = semaphore_create(sem_port, &sem_exit, SYNC_POLICY_FIFO, 0);
  if (ret != KERN_SUCCESS) {
wafwerar's avatar
wafwerar 已提交
107
    fprintf(stderr, "==%s[%d]%s()==failed to create sem_exit\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__);
108 109 110 111 112 113 114 115 116
    sem_inited = -1;
    return NULL;
  }
  sem_inited = 1;
  semaphore_wait(sem_exit);
  return NULL;
}

static void once_init(void) {
S
TD-4088  
Shengliang Guan 已提交
117
  int r = 0;
wafwerar's avatar
wafwerar 已提交
118
  r = taosThreadCreate(&sem_thread, NULL, sem_thread_routine, NULL);
119
  if (r) {
wafwerar's avatar
wafwerar 已提交
120
    fprintf(stderr, "==%s[%d]%s()==failed to create thread\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__);
121 122
    return;
  }
S
Shengliang Guan 已提交
123
  while (sem_inited == 0) {
124 125 126 127 128
    ;
  }
}
#endif

F
freemine 已提交
129
struct tsem_s {
130
#ifdef SEM_USE_PTHREAD
L
Liu Jicong 已提交
131 132
  TdThreadMutex    lock;
  TdThreadCond     cond;
S
Shengliang Guan 已提交
133
  volatile int64_t val;
134
#elif defined(SEM_USE_POSIX)
S
Shengliang Guan 已提交
135
  size_t        id;
L
Liu Jicong 已提交
136
  sem_t        *sem;
137
#elif defined(SEM_USE_SEM)
S
Shengliang Guan 已提交
138 139 140 141
  semaphore_t sem;
#else   // SEM_USE_PTHREAD
  dispatch_semaphore_t sem;
#endif  // SEM_USE_PTHREAD
142

S
Shengliang Guan 已提交
143
  volatile unsigned int valid : 1;
F
freemine 已提交
144 145
};

S
TD-4088  
Shengliang Guan 已提交
146
int tsem_init(tsem_t *sem, int pshared, unsigned int value) {
wafwerar's avatar
wafwerar 已提交
147
  // fprintf(stderr, "==%s[%d]%s():[%p]==creating\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
148
  if (*sem) {
L
Liu Jicong 已提交
149 150
    fprintf(stderr, "==%s[%d]%s():[%p]==already initialized\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
F
freemine 已提交
151
    abort();
S
slguan 已提交
152
  }
wafwerar's avatar
wafwerar 已提交
153
  struct tsem_s *p = (struct tsem_s *)taosMemoryCalloc(1, sizeof(*p));
F
freemine 已提交
154
  if (!p) {
wafwerar's avatar
wafwerar 已提交
155
    fprintf(stderr, "==%s[%d]%s():[%p]==out of memory\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
156 157 158
    abort();
  }

159
#ifdef SEM_USE_PTHREAD
wafwerar's avatar
wafwerar 已提交
160
  int r = taosThreadMutexInit(&p->lock, NULL);
161 162
  do {
    if (r) break;
wafwerar's avatar
wafwerar 已提交
163
    r = taosThreadCondInit(&p->cond, NULL);
164
    if (r) {
wafwerar's avatar
wafwerar 已提交
165
      taosThreadMutexDestroy(&p->lock);
166 167 168 169 170
      break;
    }
    p->val = value;
  } while (0);
  if (r) {
wafwerar's avatar
wafwerar 已提交
171
    fprintf(stderr, "==%s[%d]%s():[%p]==not created\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
172 173 174 175 176 177
    abort();
  }
#elif defined(SEM_USE_POSIX)
  static size_t tick = 0;
  do {
    size_t id = atomic_add_fetch_64(&tick, 1);
S
Shengliang Guan 已提交
178
    if (id == SEM_VALUE_MAX) {
179 180 181
      atomic_store_64(&tick, 0);
      id = 0;
    }
S
Shengliang Guan 已提交
182
    char name[NAME_MAX - 4];
183
    snprintf(name, sizeof(name), "/t%ld", id);
S
Shengliang Guan 已提交
184 185 186
    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 已提交
187
    int e = errno;
S
Shengliang Guan 已提交
188 189
    if (e == EEXIST) continue;
    if (e == EINTR) continue;
L
Liu Jicong 已提交
190 191
    fprintf(stderr, "==%s[%d]%s():[%p]==not created[%d]%s\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem,
            e, strerror(e));
192
    abort();
S
Shengliang Guan 已提交
193
  } while (p->sem == SEM_FAILED);
194
#elif defined(SEM_USE_SEM)
wafwerar's avatar
wafwerar 已提交
195
  taosThreadOnce(&sem_once, once_init);
S
Shengliang Guan 已提交
196
  if (sem_inited != 1) {
L
Liu Jicong 已提交
197 198
    fprintf(stderr, "==%s[%d]%s():[%p]==internal resource init failed\n", taosDirEntryBaseName(__FILE__), __LINE__,
            __func__, sem);
199 200 201
    errno = ENOMEM;
    return -1;
  }
F
freemine 已提交
202
  kern_return_t ret = semaphore_create(sem_port, &p->sem, SYNC_POLICY_FIFO, value);
203
  if (ret != KERN_SUCCESS) {
L
Liu Jicong 已提交
204 205
    fprintf(stderr, "==%s[%d]%s():[%p]==semophore_create failed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
206 207 208
    // we fail-fast here, because we have less-doc about semaphore_create for the moment
    abort();
  }
S
Shengliang Guan 已提交
209
#else   // SEM_USE_PTHREAD
F
freemine 已提交
210 211
  p->sem = dispatch_semaphore_create(value);
  if (p->sem == NULL) {
wafwerar's avatar
wafwerar 已提交
212
    fprintf(stderr, "==%s[%d]%s():[%p]==not created\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
213 214
    abort();
  }
S
Shengliang Guan 已提交
215
#endif  // SEM_USE_PTHREAD
216

F
freemine 已提交
217 218 219
  p->valid = 1;

  *sem = p;
S
slguan 已提交
220 221 222 223

  return 0;
}

S
TD-4088  
Shengliang Guan 已提交
224
int tsem_wait(tsem_t *sem) {
F
freemine 已提交
225
  if (!*sem) {
wafwerar's avatar
wafwerar 已提交
226
    fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
227 228 229 230
    abort();
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
wafwerar's avatar
wafwerar 已提交
231
    fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
232 233
    abort();
  }
234
#ifdef SEM_USE_PTHREAD
wafwerar's avatar
wafwerar 已提交
235
  if (taosThreadMutexLock(&p->lock)) {
L
Liu Jicong 已提交
236 237
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
238 239 240 241
    abort();
  }
  p->val -= 1;
  if (p->val < 0) {
wafwerar's avatar
wafwerar 已提交
242
    if (taosThreadCondWait(&p->cond, &p->lock)) {
L
Liu Jicong 已提交
243 244
      fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
              sem);
245 246 247
      abort();
    }
  }
wafwerar's avatar
wafwerar 已提交
248
  if (taosThreadMutexUnlock(&p->lock)) {
L
Liu Jicong 已提交
249 250
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
251 252 253 254 255 256 257
    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 已提交
258
#else   // SEM_USE_PTHREAD
F
freemine 已提交
259
  return dispatch_semaphore_wait(p->sem, DISPATCH_TIME_FOREVER);
S
Shengliang Guan 已提交
260
#endif  // SEM_USE_PTHREAD
S
slguan 已提交
261 262
}

S
TD-4088  
Shengliang Guan 已提交
263
int tsem_post(tsem_t *sem) {
F
freemine 已提交
264
  if (!*sem) {
wafwerar's avatar
wafwerar 已提交
265
    fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
266 267 268 269
    abort();
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
wafwerar's avatar
wafwerar 已提交
270
    fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
271 272
    abort();
  }
273
#ifdef SEM_USE_PTHREAD
wafwerar's avatar
wafwerar 已提交
274
  if (taosThreadMutexLock(&p->lock)) {
L
Liu Jicong 已提交
275 276
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
277 278 279 280
    abort();
  }
  p->val += 1;
  if (p->val <= 0) {
wafwerar's avatar
wafwerar 已提交
281
    if (taosThreadCondSignal(&p->cond)) {
L
Liu Jicong 已提交
282 283
      fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
              sem);
284 285 286
      abort();
    }
  }
wafwerar's avatar
wafwerar 已提交
287
  if (taosThreadMutexUnlock(&p->lock)) {
L
Liu Jicong 已提交
288 289
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
290 291 292 293 294 295 296
    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 已提交
297
#else   // SEM_USE_PTHREAD
F
freemine 已提交
298
  return dispatch_semaphore_signal(p->sem);
S
Shengliang Guan 已提交
299
#endif  // SEM_USE_PTHREAD
F
freemine 已提交
300 301
}

S
TD-4088  
Shengliang Guan 已提交
302
int tsem_destroy(tsem_t *sem) {
wafwerar's avatar
wafwerar 已提交
303
  // fprintf(stderr, "==%s[%d]%s():[%p]==destroying\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
304
  if (!*sem) {
wafwerar's avatar
wafwerar 已提交
305
    // fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
306
    // abort();
F
freemine 已提交
307 308 309 310
    return 0;
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
L
Liu Jicong 已提交
311 312
    // fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
    // sem); abort();
313 314 315
    return 0;
  }
#ifdef SEM_USE_PTHREAD
wafwerar's avatar
wafwerar 已提交
316
  if (taosThreadMutexLock(&p->lock)) {
L
Liu Jicong 已提交
317 318
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
319 320 321
    abort();
  }
  p->valid = 0;
wafwerar's avatar
wafwerar 已提交
322
  if (taosThreadCondDestroy(&p->cond)) {
L
Liu Jicong 已提交
323 324
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
325 326
    abort();
  }
wafwerar's avatar
wafwerar 已提交
327
  if (taosThreadMutexUnlock(&p->lock)) {
L
Liu Jicong 已提交
328 329
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
330 331
    abort();
  }
wafwerar's avatar
wafwerar 已提交
332
  if (taosThreadMutexDestroy(&p->lock)) {
L
Liu Jicong 已提交
333 334
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__,
            sem);
335 336 337
    abort();
  }
#elif defined(SEM_USE_POSIX)
S
Shengliang Guan 已提交
338
  char name[NAME_MAX - 4];
339
  snprintf(name, sizeof(name), "/t%ld", p->id);
S
TD-4088  
Shengliang Guan 已提交
340
  int r = sem_unlink(name);
341
  if (r) {
S
TD-4088  
Shengliang Guan 已提交
342
    int e = errno;
L
Liu Jicong 已提交
343 344
    fprintf(stderr, "==%s[%d]%s():[%p]==unlink failed[%d]%s\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem,
            e, strerror(e));
F
freemine 已提交
345 346
    abort();
  }
347 348
#elif defined(SEM_USE_SEM)
  semaphore_destroy(sem_port, p->sem);
S
Shengliang Guan 已提交
349 350
#else   // SEM_USE_PTHREAD
#endif  // SEM_USE_PTHREAD
F
freemine 已提交
351 352

  p->valid = 0;
wafwerar's avatar
wafwerar 已提交
353
  taosMemoryFree(p);
F
freemine 已提交
354 355

  *sem = NULL;
S
slguan 已提交
356 357
  return 0;
}
F
freemine 已提交
358

wafwerar's avatar
wafwerar 已提交
359
bool taosCheckPthreadValid(TdThread thread) {
F
freemine 已提交
360
  uint64_t id = 0;
wafwerar's avatar
wafwerar 已提交
361
  int      r = TdThreadhreadid_np(thread, &id);
F
freemine 已提交
362 363 364 365
  return r ? false : true;
}

int64_t taosGetSelfPthreadId() {
366
  uint64_t id;
wafwerar's avatar
wafwerar 已提交
367
  TdThreadhreadid_np(0, &id);
S
Shengliang Guan 已提交
368
  return (int64_t)id;
F
freemine 已提交
369 370
}

wafwerar's avatar
wafwerar 已提交
371
int64_t taosGetPthreadId(TdThread thread) { return (int64_t)thread; }
F
freemine 已提交
372

wafwerar's avatar
wafwerar 已提交
373
void taosResetPthread(TdThread *thread) { *thread = NULL; }
F
freemine 已提交
374

wafwerar's avatar
wafwerar 已提交
375
bool taosComparePthread(TdThread first, TdThread second) { return taosThreadEqual(first, second) ? true : false; }
F
freemine 已提交
376

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

379
int32_t taosGetAppName(char *name, int32_t *len) {
S
Shengliang Guan 已提交
380
  char buf[PATH_MAX + 1];
F
freemine 已提交
381
  buf[0] = '\0';
S
Shengliang Guan 已提交
382
  proc_name(getpid(), buf, sizeof(buf) - 1);
F
freemine 已提交
383 384 385 386 387 388 389
  buf[PATH_MAX] = '\0';
  size_t n = strlen(buf);
  if (len) *len = n;
  if (name) strcpy(name, buf);
  return 0;
}

S
Shengliang Guan 已提交
390 391 392 393 394 395 396
#else

/*
 * linux implementation
 */

#include <sys/syscall.h>
S
Shengliang Guan 已提交
397
#include <unistd.h>
S
Shengliang Guan 已提交
398

wafwerar's avatar
wafwerar 已提交
399
bool taosCheckPthreadValid(TdThread thread) { return thread != 0; }
S
Shengliang Guan 已提交
400 401 402 403 404 405 406 407

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

wafwerar's avatar
wafwerar 已提交
408 409 410
int64_t taosGetPthreadId(TdThread thread) { return (int64_t)thread; }
void    taosResetPthread(TdThread* thread) { *thread = 0; }
bool    taosComparePthread(TdThread first, TdThread second) { return first == second; }
S
Shengliang Guan 已提交
411 412
int32_t taosGetPId() { return getpid(); }

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

S
Shengliang Guan 已提交
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
  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;
}

L
Liu Jicong 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458
int32_t tsem_timewait(tsem_t* sem, int64_t nanosecs) {
  int ret = 0;

  struct timespec tv = {
      .tv_sec = 0,
      .tv_nsec = nanosecs,
  };

  while ((ret = sem_timedwait(sem, &tv)) == -1 && errno == EINTR) continue;

  return ret;
}

S
Shengliang Guan 已提交
459
#endif