📄 sync.cpp
字号:
#include "sync.h"
#undef _DEBUG
class Tracer
{
FILE *tr_file;
mutex_t mtx;
char *filename;
public:
Tracer(char *file) {
#ifdef _DEBUG
tr_file = fopen(file, "w");
if (!tr_file) {
fprintf (stderr, "Cannot start tracing");
} else {
Trace ("Tracer started");
}
#endif
}
~Tracer() {
#ifdef _DEBUG
if (tr_file) {
fclose(tr_file);
}
#endif
}
void Trace(char *msg) {
#ifdef _DEBUG
if (tr_file){
critical_section cs(mtx);
fprintf (tr_file, "%s\n", msg);
fflush(tr_file);
}
#endif
}
};
static Tracer SyncTracer("sync_cpp.log");
CtkThreadPool CtkThreadPool::instance;
CtkThreadPool::CtkThreadPool()
{
SyncTracer.Trace("CtkThreadPool c-tor");
threads_count = 0;
chain = NULL;
mallocList = NULL;
lastHeader = NULL;
CtkAllocHeader* hdr = (CtkAllocHeader*)malloc(sizeof(CtkAllocHeader) + sizeof(CtkThread));
hdr->next = NULL;
hdr->finalizer = CtkFinalizer(ctkDeleteThread);
mainThread = (CtkThread*)(hdr+1);
ctkInitializeThread(mainThread);
#ifdef _WIN32
threadKey = TlsAlloc();
#else
pthread_key_create(&threadKey, NULL);
#endif
setupThread(mainThread);
SyncTracer.Trace("End of CtkThreadPool c-tor");
}
void CtkThreadPool::setupThread(CtkThread* thr)
{
#ifdef _WIN32
TlsSetValue(threadKey, thr);
#else
pthread_setspecific(threadKey, thr);
#endif
}
void CtkThreadPool::addThread(CtkThread* thr) {
SyncTracer.Trace("addThread");
critical_section cs(mutex);
SyncTracer.Trace("addThread: mutex locked");
thr->next = chain;
chain = thr;
threads_count += 1;
SyncTracer.Trace("End addThread");
}
void CtkThreadPool::removeThread(CtkThread* thr) {
SyncTracer.Trace("removeThread");
critical_section cs(mutex);
CtkThread *tp, **tpp = &chain;
while ((tp = *tpp) != thr) {
tpp = &tp->next;
}
delete[] tp->stack;
tp->stack = NULL;
tp->sp = 0;
*tpp = tp->next;
if (thr->mallocList != NULL) {
*thr->lastHeader = mallocList;
lastHeader = thr->lastHeader;
mallocList = thr->mallocList;
thr->mallocList = NULL;
}
threads_count -= 1;
SyncTracer.Trace("End removeThread");
}
int CtkThreadPool::ThreadsCount(void)
{
SyncTracer.Trace("ThreadsCount");
critical_section cs(mutex);
SyncTracer.Trace("End ThreadsCount");
return threads_count;
}
bool CtkThreadPool::IsEmpty(int count)
{
SyncTracer.Trace("IsEmpty");
// critical_section cs(mutex);
if (threads_count > count) {
SyncTracer.Trace("End IsEmpty - false");
return false;
}
else {
SyncTracer.Trace("End IsEmpty - true");
return true;
}
}
void CtkThreadPool::ThreadHanged(void)
{
/*
SyncTracer.Trace("ThreadHanged");
critical_section cs(mutex);
threads_count -= 1;
SyncTracer.Trace("End ThreadHanged");
*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -