📄 sync.h
字号:
#ifndef __SYNC_H__
#define __SYNC_H__
#include "ctalk.h"
#ifdef _WIN32
class mutex_t {
CRITICAL_SECTION cs;
public:
void lock() {
EnterCriticalSection(&cs);
}
void unlock() {
LeaveCriticalSection(&cs);
}
mutex_t() {
InitializeCriticalSection(&cs);
}
~mutex_t() {
DeleteCriticalSection(&cs);
}
};
class event_t {
HANDLE h;
public:
event_t() {
h = CreateEvent(NULL, FALSE, FALSE, NULL);
}
~event_t() {
CloseHandle(h);
}
void signal() {
SetEvent(h);
}
void wait(mutex_t& m) {
m.unlock();
WaitForSingleObject(h, INFINITE);
m.lock();
}
};
#else
class mutex_t {
int count;
pthread_t owner;
pthread_mutex_t cs;
friend class event_t;
public:
void lock() {
pthread_t self = pthread_self();
if (owner != self) {
pthread_mutex_lock(&cs);
owner = self;
}
count += 1;
}
void unlock() {
assert(pthread_self() == owner);
if (--count == 0) {
owner = 0;
pthread_mutex_unlock(&cs);
}
}
mutex_t() {
pthread_mutex_init(&cs, NULL);
}
~mutex_t() {
pthread_mutex_destroy(&cs);
}
};
class event_t {
pthread_cond_t cond;
public:
event_t() {
pthread_cond_init(&cond, NULL);
}
~event_t() {
pthread_cond_destroy(&cond);
}
void signal() {
pthread_cond_signal(&cond);
}
void wait(mutex_t& m) {
pthread_t self = pthread_self();
assert(m.owner == self && m.count == 1);
m.count = 0;
m.owner = 0;
pthread_cond_wait(&cond, &m.cs);
m.count = 1;
m.owner = self;
}
};
#endif
class critical_section {
mutex_t& mutex;
public:
critical_section(mutex_t& m) : mutex(m) {
m.lock();
}
~critical_section() {
mutex.unlock();
}
};
class CtkThreadPool {
friend class CtkMemoryManager;
mutex_t mutex;
CtkThread* chain;
CtkAllocHeader* mallocList;
CtkAllocHeader** lastHeader;
CtkThread* mainThread;
// Added by KDB
int threads_count;
public:
#ifdef _WIN32
int threadKey;
#else
pthread_key_t threadKey;
#endif
CtkThreadPool();
void addThread(CtkThread* thr);
void setupThread(CtkThread* thr);
void removeThread(CtkThread* thr);
void pushVariable(CtkObject obj) {
mainThread->stack[mainThread->sp++] = obj;
}
// Added by KDB
int ThreadsCount(void);
bool IsEmpty(int count);
void ThreadHanged(void);
static CtkThreadPool instance;
};
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -