osSemaphore.c 11.6 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
  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 已提交
102
    fprintf(stderr, "==%s[%d]%s()==failed to create sem_exit\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__);
103 104 105 106 107 108 109 110 111
    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
  r = pthread_create(&sem_thread, NULL, sem_thread_routine, NULL);
  if (r) {
wafwerar's avatar
wafwerar 已提交
115
    fprintf(stderr, "==%s[%d]%s()==failed to create thread\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__);
116 117
    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) {
wafwerar's avatar
wafwerar 已提交
142
  // fprintf(stderr, "==%s[%d]%s():[%p]==creating\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
143
  if (*sem) {
wafwerar's avatar
wafwerar 已提交
144
    fprintf(stderr, "==%s[%d]%s():[%p]==already initialized\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
145
    abort();
S
slguan 已提交
146
  }
S
Shengliang Guan 已提交
147
  struct tsem_s *p = (struct tsem_s *)calloc(1, sizeof(*p));
F
freemine 已提交
148
  if (!p) {
wafwerar's avatar
wafwerar 已提交
149
    fprintf(stderr, "==%s[%d]%s():[%p]==out of memory\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
150 151 152
    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
  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) {
wafwerar's avatar
wafwerar 已提交
165
    fprintf(stderr, "==%s[%d]%s():[%p]==not created\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
166 167 168 169 170 171
    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
    if (e == EEXIST) continue;
    if (e == EINTR) continue;
wafwerar's avatar
wafwerar 已提交
184
    fprintf(stderr, "==%s[%d]%s():[%p]==not created[%d]%s\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem, e,
S
Shengliang Guan 已提交
185
            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) {
wafwerar's avatar
wafwerar 已提交
191
    fprintf(stderr, "==%s[%d]%s():[%p]==internal resource init failed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
192 193 194
    errno = ENOMEM;
    return -1;
  }
F
freemine 已提交
195
  kern_return_t ret = semaphore_create(sem_port, &p->sem, SYNC_POLICY_FIFO, value);
196
  if (ret != KERN_SUCCESS) {
wafwerar's avatar
wafwerar 已提交
197
    fprintf(stderr, "==%s[%d]%s():[%p]==semophore_create failed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
198 199 200
    // 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
  p->sem = dispatch_semaphore_create(value);
  if (p->sem == NULL) {
wafwerar's avatar
wafwerar 已提交
204
    fprintf(stderr, "==%s[%d]%s():[%p]==not created\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
205 206
    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
  if (!*sem) {
wafwerar's avatar
wafwerar 已提交
218
    fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
219 220 221 222
    abort();
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
wafwerar's avatar
wafwerar 已提交
223
    fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
224 225
    abort();
  }
226 227
#ifdef SEM_USE_PTHREAD
  if (pthread_mutex_lock(&p->lock)) {
wafwerar's avatar
wafwerar 已提交
228
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
229 230 231 232 233
    abort();
  }
  p->val -= 1;
  if (p->val < 0) {
    if (pthread_cond_wait(&p->cond, &p->lock)) {
wafwerar's avatar
wafwerar 已提交
234
      fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
235 236 237 238
      abort();
    }
  }
  if (pthread_mutex_unlock(&p->lock)) {
wafwerar's avatar
wafwerar 已提交
239
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
240 241 242 243 244 245 246
    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
  if (!*sem) {
wafwerar's avatar
wafwerar 已提交
254
    fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
255 256 257 258
    abort();
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
wafwerar's avatar
wafwerar 已提交
259
    fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
260 261
    abort();
  }
262 263
#ifdef SEM_USE_PTHREAD
  if (pthread_mutex_lock(&p->lock)) {
wafwerar's avatar
wafwerar 已提交
264
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
265 266 267 268 269
    abort();
  }
  p->val += 1;
  if (p->val <= 0) {
    if (pthread_cond_signal(&p->cond)) {
wafwerar's avatar
wafwerar 已提交
270
      fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
271 272 273 274
      abort();
    }
  }
  if (pthread_mutex_unlock(&p->lock)) {
wafwerar's avatar
wafwerar 已提交
275
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
276 277 278 279 280 281 282
    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) {
wafwerar's avatar
wafwerar 已提交
289
  // fprintf(stderr, "==%s[%d]%s():[%p]==destroying\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
F
freemine 已提交
290
  if (!*sem) {
wafwerar's avatar
wafwerar 已提交
291
    // fprintf(stderr, "==%s[%d]%s():[%p]==not initialized\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
292
    // abort();
F
freemine 已提交
293 294 295 296
    return 0;
  }
  struct tsem_s *p = *sem;
  if (!p->valid) {
wafwerar's avatar
wafwerar 已提交
297
    // fprintf(stderr, "==%s[%d]%s():[%p]==already destroyed\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
298 299 300 301 302
    // abort();
    return 0;
  }
#ifdef SEM_USE_PTHREAD
  if (pthread_mutex_lock(&p->lock)) {
wafwerar's avatar
wafwerar 已提交
303
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
304 305 306 307
    abort();
  }
  p->valid = 0;
  if (pthread_cond_destroy(&p->cond)) {
wafwerar's avatar
wafwerar 已提交
308
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
309 310 311
    abort();
  }
  if (pthread_mutex_unlock(&p->lock)) {
wafwerar's avatar
wafwerar 已提交
312
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
313 314 315
    abort();
  }
  if (pthread_mutex_destroy(&p->lock)) {
wafwerar's avatar
wafwerar 已提交
316
    fprintf(stderr, "==%s[%d]%s():[%p]==internal logic error\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem);
317 318 319
    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;
wafwerar's avatar
wafwerar 已提交
325
    fprintf(stderr, "==%s[%d]%s():[%p]==unlink failed[%d]%s\n", taosDirEntryBaseName(__FILE__), __LINE__, __func__, sem, e,
S
Shengliang Guan 已提交
326
            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