EventLoop的基本接口包括构造、析构、loop()。 One Loop Per Thread 一个线程只有一个EventLoop对象、如果当前线程创建了其他 EventLoop对象,则终止程序.
CurrentThread 通过__thread 关键字和系统调用syscall() 保存获取线程的的pid(不通于线程tid,tid属于进程,进程内唯一,线程pid属于内核).
#ifndef _CURRENT_THREAD #define _CURRENT_THREAD #include <stdint.h> #include <stdio.h> #include <sys/syscall.h> #include <pthread.h> #include <unistd.h> namespace CurrentThread { // internal extern __thread int t_cachedTid; extern __thread char t_tidString[32]; extern __thread int t_tidStringLength; extern __thread const char* t_threadName; inline int tid() { if (__builtin_expect(t_cachedTid == 0, 0)) { if (t_cachedTid == 0) { t_cachedTid = static_cast<pid_t>(::syscall(SYS_gettid)); t_tidStringLength = snprintf(t_tidString, sizeof t_tidString, "%5d ", t_cachedTid); } } return t_cachedTid; } inline const char* tidString() // for logging { return t_tidString; } inline int tidStringLength() // for logging { return t_tidStringLength; } inline const char* name() { return t_threadName; } } #endif //CurrentThread.cpp #include "CurrentThread.hh" namespace CurrentThread { __thread int t_cachedTid = 0; __thread char t_tidString[32]; __thread int t_tidStringLength = 6; __thread const char* t_threadName = "unknown"; }
每个线程至多有一个EventLoop对象,那么我们通过static 成员函数getEventLoopOfCurrentThread() 返回此对象.
EventLoop* EventLoop::getEventLoopOfCurrentThread() { return t_loopInThisThread; }
test1
正确的逻辑.
#include <errno.h> #include "EventLoop.hh" #include <thread> int main() { EventLoop testloop; testloop.loop(); return 0; } ./test.out 2018-10-25 20:01:03.287601 [TRACE] [EventLoop.cpp:12] [EventLoop] EventLoop Create 0x7FFF7B1E2780 in thread 2086 2018-10-25 20:01:03.287750 [TRACE] [EventLoop.cpp:36] [loop] EventLoop 0x7FFF7B1E2780 start loopig 2018-10-25 20:01:06.291622 [TRACE] [EventLoop.cpp:40] [loop] EventLoop 0x7FFF7B1E2780 stop loopigtest2
企图在当前线程启用其他线程创建的EventLoop对象
#include <errno.h> #include "EventLoop.hh" #include <thread> EventLoop* g_loop; void test() { g_loop->loop(); } int main() { EventLoop testloop; //testloop.loop(); g_loop = &testloop; std::thread test_thread(test); test_thread.join(); return 0; } ./test.out 2018-10-25 20:05:49.618701 [TRACE] [EventLoop.cpp:12] [EventLoop] EventLoop Create 0x7FFCA55A35F0 in thread 2114 2018-10-25 20:05:49.619057 [FATAL] [EventLoop.cpp:47] EventLoop::abortNotInLoopThread - EventLoop 0x7FFCA55A35F0 was created in threadId_ = 2114, current thread id = 2115 Aborted (core dumped)
