第三方框架改为仓内子集并完善构建忽略规则

完整 NIM_Duilib_Framework 仓库移至父目录,third_party 仅保留实际使用的 base、duilib、bin/resources 与许可证;.gitignore 覆盖 MSBuild 与打包产物。
This commit is contained in:
tongtong committed 2026-11-15 08:54:17 +08:00
1 parent 249e8548de
commit e1e26acc49
391 files changed
+342850

No files matched your search

@@ -0,0 +1,291 @@
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: rl
// Date: 2011/6/29
//
// Enhanced by: wrt(guangguang)
//
// Thread with framework(message loop)
#include "framework_thread.h"
#include "base/base_types.h"
#include "base/macros.h"
#include "base/memory/lazy_instance.h"
//#include "base/log/log.h"
namespace nbase
{
// We use this thread-local variable to record whether or not a thread exited
// because its Stop method was called. This allows us to catch cases where
// MessageLoop::Quit() is called directly, which is unexpected when using a
// Thread to setup and run a MessageLoop.
nbase::LazyInstance<nbase::ThreadLocalPointer<FrameworkThreadTlsData> > lazy_tls_data;
FrameworkThread::FrameworkThread(const char* name)
: started_(false),
stopping_(false),
loop_type_(MessageLoop::kDefaultMessageLoop),
message_loop_(NULL),
event_(false, false),
name_(name)
{
}
FrameworkThread::~FrameworkThread()
{
Stop();
}
bool FrameworkThread::Start()
{
return StartWithLoop(MessageLoop::kDefaultMessageLoop);
}
#if defined(OS_WIN)
bool FrameworkThread::StartWithLoop(const MessageLoop::Type type, Dispatcher *dispatcher)
#else
bool FrameworkThread::StartWithLoop(const MessageLoop::Type type)
#endif
{
if (message_loop_ != NULL)
return false;
loop_type_ = type;
#if defined(OS_WIN)
dispatcher_ = dispatcher;
#endif
if (Create() == false)
return false;
// Wait for the thread to start and initialize message_loop_
event_.Wait();
started_ = true;
return true;
}
#if defined(OS_WIN)
bool FrameworkThread::StartWithLoop(CustomMessageLoopFactory *factory, Dispatcher *dispatcher)
#else
bool FrameworkThread::StartWithLoop(CustomMessageLoopFactory *factory)
#endif
{
if (factory == NULL)
return false;
factory_.reset(factory);
loop_type_ = MessageLoop::kCustomMessageLoop;
#if defined(OS_WIN)
dispatcher_ = dispatcher;
#endif
if (!Create())
return false;
// Wait for the thread to start and initialize message_loop_
event_.Wait();
started_ = true;
return true;
}
#if defined(OS_WIN)
void FrameworkThread::RunOnCurrentThreadWithLoop(const MessageLoop::Type type, Dispatcher *dispatcher)
#else
void FrameworkThread::RunOnCurrentThreadWithLoop(const MessageLoop::Type type)
#endif
{
loop_type_ = type;
started_ = true;
#if defined(OS_WIN)
dispatcher_ = dispatcher;
#endif
Run();
}
void FrameworkThread::Stop()
{
if (!thread_was_started())
return;
StopSoon();
// Wait for the thread to exit.
Close();
started_ = false;
stopping_ = false;
}
void FrameworkThread::StopSoon()
{
if (stopping_ || !message_loop_)
return;
stopping_ = true;
message_loop_->PostNonNestableTask(
nbase::Bind(&FrameworkThread::DoStopSoon, this));
}
void FrameworkThread::DoStopSoon()
{
MessageLoop::current()->Quit();
SetThreadWasQuitProperly(true);
}
void FrameworkThread::Run()
{
#ifndef NDEBUG
#if defined(OS_WIN) && defined(COMPILER_MSVC)
SetThreadName(GetCurrentThreadId(), name_.c_str());
#endif
#endif
InitTlsData(this);
SetThreadWasQuitProperly(false);
{
ThreadId thread_id = Thread::CurrentId();
set_thread_id(thread_id);
// The message loop for this thread.
MessageLoop *message_loop;
if (loop_type_ == MessageLoop::kCustomMessageLoop)
message_loop = factory_->CreateMessageLoop();
else {
if (loop_type_ == MessageLoop::kIOMessageLoop)
message_loop = new IOMessageLoop;
#if defined(OS_WIN)
else if (loop_type_ == MessageLoop::kUIMessageLoop)
message_loop = new UIMessageLoop;
#endif
else
message_loop = new MessageLoop;
}
message_loop_ = message_loop;
// Let the thread do extra initialization.
// Let's do this before signaling we are started.
Init();
event_.Signal();
#if defined(OS_WIN)
message_loop_->RunWithDispatcher(dispatcher_);
#else
message_loop_->Run();
#endif // OS_WIN
// Let the thread do extra cleanup.
Cleanup();
//DCHECK(GetThreadWasQuitProperly());
// We can't receive messages anymore.
if (loop_type_ != MessageLoop::kCustomMessageLoop)
delete message_loop_;
else
{
delete message_loop_;
factory_.reset();
}
message_loop_ = NULL;
}
set_thread_id(kInvalidThreadId);
{
FrameworkThreadTlsData *tls = GetTlsData();
if (tls != NULL)
{ }
//DCHECK(tls->managed == 0); // you must call ThreadManager::UnregisterThread before come there
}
FreeTlsData();
}
void FrameworkThread::InitTlsData(FrameworkThread *self)
{
FrameworkThreadTlsData *tls = GetTlsData();
//DCHECK(tls == NULL);
if (tls != NULL)
return;
tls = new FrameworkThreadTlsData;
tls->self = self;
tls->managed = 0;
tls->managed_thread_id = -1;
tls->quit_properly = false;
tls->custom_data = NULL;
lazy_tls_data.Pointer()->Set(tls);
}
void FrameworkThread::FreeTlsData()
{
FrameworkThreadTlsData *tls = GetTlsData();
//DCHECK(tls != NULL);
if (tls == NULL)
return;
lazy_tls_data.Pointer()->Set(NULL);
delete tls;
}
FrameworkThreadTlsData* FrameworkThread::GetTlsData()
{
return lazy_tls_data.Pointer()->Get();
}
bool FrameworkThread::GetThreadWasQuitProperly()
{
FrameworkThreadTlsData *tls = GetTlsData();
//DCHECK(tls != NULL);
if (tls == NULL)
return false;
return tls->quit_properly;
}
void FrameworkThread::SetThreadWasQuitProperly(bool flag)
{
FrameworkThreadTlsData *tls = GetTlsData();
//DCHECK(tls != NULL);
if (tls == NULL)
return;
tls->quit_properly = flag;
}
FrameworkThread* FrameworkThread::current()
{
FrameworkThreadTlsData *tls = GetTlsData();
//DCHECK(tls != NULL);
if (tls == NULL)
return NULL;
return tls->self;
}
int FrameworkThread::GetManagedThreadId()
{
FrameworkThreadTlsData *tls = GetTlsData();
//DCHECK(tls != NULL);
if (tls == NULL)
return -1;
return tls->managed_thread_id;
}
void* FrameworkThread::GetCustomTlsData()
{
FrameworkThreadTlsData *tls = GetTlsData();
//DCHECK(tls != NULL);
if (tls == NULL)
return NULL;
return tls->custom_data;
}
void FrameworkThread::SetCustomTlsData(void *data)
{
FrameworkThreadTlsData *tls = GetTlsData();
//DCHECK(tls != NULL);
if (tls == NULL)
return;
tls->custom_data = data;
}
} // namespace nbase
@@ -0,0 +1,207 @@
// Thread with framework(message loop)
#ifndef BASE_THREAD_FRAMEWORK_THREAD_H_
#define BASE_THREAD_FRAMEWORK_THREAD_H_
#include "thread.h"
#include "thread_local.h"
#include "base/framework/message_loop.h"
#include "base/synchronization/waitable_event.h"
namespace nbase
{
class FrameworkThread;
struct FrameworkThreadTlsData
{
FrameworkThread *self; // A pointer pointed to the thread itself
bool quit_properly; // the thread quit properly
int managed; // reference counter, the framework thread is managed by ThreadManager
int managed_thread_id; // if a thread is managered, this will be the manager id of it (may not be a thread id)
void *custom_data; // reserved for the derived classes of FrameworkThread
};
// A simple thread abstraction that establishes a MessageLoop on a new thread.
// The consumer uses the MessageLoop of the thread to cause code to execute on
// the thread. When this object is destroyed the thread is terminated. All
// pending tasks queued on the thread's message loop will run to completion
// before the thread is terminated.
//
// After the thread is stopped, the destruction sequence is:
//
// (1) FrameworkThread::CleanUp()
// (2) MessageLoop::~MessageLoop
// (3.b) MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop
class BASE_EXPORT FrameworkThread : public virtual nbase::SupportWeakCallback, public nbase::Thread
{
friend class ThreadMap;
friend class ThreadManager;
public:
// custom message loop
class CustomMessageLoop : public MessageLoop
{
public:
virtual ~CustomMessageLoop() {}
};
// custom message loop factory
class CustomMessageLoopFactory
{
public:
virtual CustomMessageLoop* CreateMessageLoop() = 0;
};
explicit FrameworkThread(const char* name);
virtual ~FrameworkThread();
// Starts the thread. Returns true if the thread was successfully started;
// otherwise, returns false. Upon successful return, the message_loop()
// getter will return non-null.
//
// Note: This function can't be called on Windows with the loader lock held;
// i.e. during a DllMain, global object construction or destruction, atexit()
// callback.
bool Start();
// Starts the thread. Behaves exactly like Start in addition to allow to
// override the default loop type.
//
// Note: This function can't be called on Windows with the loader lock held;
// i.e. during a DllMain, global object construction or destruction, atexit()
// callback.
#if defined(OS_WIN)
bool StartWithLoop(const MessageLoop::Type type, Dispatcher *dispatcher = NULL);
bool StartWithLoop(CustomMessageLoopFactory *factory, Dispatcher *dispatcher = NULL);
#else
bool StartWithLoop(const MessageLoop::Type type);
bool StartWithLoop(CustomMessageLoopFactory *factory);
#endif // OS_WIN
// Create a message loop and run it on current thread
// Do be sure that the current thread is a crt thread (created by _beginthreadex, etc.) if OS = Windows
#if defined(OS_WIN)
void RunOnCurrentThreadWithLoop(const MessageLoop::Type type, Dispatcher *dispatcher = NULL);
#else
void RunOnCurrentThreadWithLoop(const MessageLoop::Type type);
#endif // OS_WIN
// Signals the thread to exit and returns once the thread has exited. After
// this method returns, the Thread object is completely reset and may be used
// as if it were newly constructed (i.e., Start may be called again).
//
// Stop may be called multiple times and is simply ignored if the thread is
// already stopped.
//
// NOTE: This method is optional. It is not strictly necessary to call this
// method as the Thread's destructor will take care of stopping the thread if
// necessary.
//
void Stop();
// Signals the thread to exit in the near future.
//
// WARNING: This function is not meant to be commonly used. Use at your own
// risk. Calling this function will cause message_loop() to become invalid in
// the near future. This function was created to workaround a specific
// deadlock on Windows with printer worker thread. In any other case, Stop()
// should be used.
//
// StopSoon should not be called multiple times as it is risky to do so. It
// could cause a timing issue in message_loop() access. Call Stop() to reset
// the thread object once it is known that the thread has quit.
void StopSoon();
// Returns the message loop for this thread. Use the MessageLoop's
// PostTask methods to execute code on the thread. This only returns
// non-null after a successful call to Start. After Stop has been called,
// this will return NULL.
//
// NOTE: You must not call this MessageLoop's Quit method directly. Use
// the Thread's Stop method instead.
//
MessageLoop* message_loop() const { return message_loop_; }
// Set the name of this thread (for display in debugger too).
const std::string &thread_name() { return name_; }
// Returns true if the thread has been started, and not yet stopped.
// When a thread is running, |thread_id_| is a valid id.
bool IsRunning() const { return (Thread::thread_id() != kInvalidThreadId) ? true : false; }
// Returns true if the thread's stopping flag is set
bool IsStopping() const { return stopping_; }
// Get the current thread
// must be called in Run or in its children methods
static FrameworkThread* current();
// Get the managed thread id of current thread
// return -1 means current thread is not managed by ThreadManager
static int GetManagedThreadId();
// Get custom tls data
static void* GetCustomTlsData();
// Set custom tls data
static void SetCustomTlsData(void *data);
protected:
// Called just prior to starting the message loop
virtual void Init() {}
// Called to start the message loop
virtual void Run();
// Called just after the message loop ends
virtual void Cleanup() {}
// Called after the message loop has been deleted. In general clients
// should prefer to use CleanUp(). This method is used when code needs to
// be run after all of the MessageLoop::DestructionObservers have completed.
virtual void CleanUpAfterMessageLoopDestruction() {}
// Initilize the tls data, must be called before any tls associated calls on current thread
static void InitTlsData(FrameworkThread *self);
// Free the tls data, must be called after any tls associated calls on current thread
static void FreeTlsData();
// Retrieve the tls data
static FrameworkThreadTlsData* GetTlsData();
static void SetThreadWasQuitProperly(bool flag);
static bool GetThreadWasQuitProperly();
void set_message_loop(MessageLoop* message_loop)
{
message_loop_ = message_loop;
}
private:
bool thread_was_started() const { return started_; }
void DoStopSoon();
// Whether we successfully started the thread.
bool started_;
// If true, we're in the middle of stopping, and shouldn't access
// |message_loop_|. It may non-NULL and invalid.
bool stopping_;
// The thread's message loop. Valid only while the thread is alive. Set
// by the created thread.
MessageLoop::Type loop_type_;
MessageLoop *message_loop_;
std::shared_ptr<CustomMessageLoopFactory> factory_;
#if defined(OS_WIN)
// the dispatcher
Dispatcher *dispatcher_;
#endif // OS_WIN
// For ensure message_loop_ has instance after thread create
WaitableEvent event_;
// The name of the thread. Used for debugging purposes.
std::string name_;
};
}
#endif // BASE_THREAD_FRAMEWORK_THREAD_H_
+99
View File
@@ -0,0 +1,99 @@
// Thread is the low-level platform-specific abstraction
// to the OS's threading interface.
#ifndef BASE_THREAD_THREAD_H_
#define BASE_THREAD_THREAD_H_
#include "base/base_config.h"
#include "base/base_export.h"
#if defined(OS_WIN)
#include <process.h>
#include <windows.h>
#else
#include <pthread.h>
#endif
#include "base/base_types.h"
namespace nbase
{
#if defined(OS_WIN)
typedef uint32_t ThreadId;
typedef void* ThreadHandle;
#elif defined(OS_POSIX)
typedef pid_t ThreadId;
typedef pthread_t ThreadHandle;
#endif
const ThreadId kInvalidThreadId = 0;
// Valid values for thread priority
enum ThreadPriority
{
kThreadPriorityDefault,
kThreadPriorityLow,
kThreadPriorityNormal,
kThreadPriorityHigh,
kThreadPriorityRealtime
};
class BASE_EXPORT Thread
{
public:
Thread();
virtual ~Thread();
// Create a thread with a option, if the option is null, thread will start with
// a default option
bool Create();
// Close the thread
void Close();
// Terminate the thread
void Terminate();
// Sleeps for the specified duration (units are milliseconds)
static void Sleep(int duration_ms);
// Yield the current thread so another thread can be scheduled
static void YieldThread();
// Gets the current thread id
static ThreadId CurrentId();
ThreadId thread_id() const { return thread_id_; }
void set_thread_id(ThreadId thread_id) { thread_id_ = thread_id; }
// Gets the current thread handle
ThreadHandle thread_handle() const { return thread_handle_; }
// Set the thread's priority
void set_thread_priority(ThreadPriority priority) { thread_priority_ = priority; }
protected:
// Thread process function
virtual void Run() {}
private:
#if defined(OS_WIN)
static uint32_t __stdcall ThreadProcFunc(void *arg);
#else
static void* ThreadProcFunc(void *arg);
#endif
ThreadId thread_id_;
ThreadHandle thread_handle_;
ThreadPriority thread_priority_;
};
#if defined(OS_WIN) && defined(COMPILER_MSVC)
BASE_EXPORT void SetThreadName(DWORD thread_id, const char* name);
#endif
}
#endif // BASE_THREAD_THREAD_H_
@@ -0,0 +1,91 @@
// This file implements some useful thread local template data structures
#ifndef BASE_THREAD_THREAD_LOCAL_H_
#define BASE_THREAD_THREAD_LOCAL_H_
#include "base/base_config.h"
#if defined(OS_POSIX)
#include <pthread.h>
#endif
#include "base/macros.h"
namespace nbase
{
namespace internal
{
struct ThreadLocalPlatform
{
#if defined(OS_WIN)
typedef unsigned long SlotType;
#elif defined(OS_POSIX)
typedef pthread_key_t SlotType;
#endif
static void AllocateSlot(SlotType &slot);
static void FreeSlot(SlotType &slot);
static void* GetValueFromSlot(SlotType &slot);
static void SetValueInSlot(SlotType &slot, void *value);
};
} // namespace internal
template<typename Type>
class ThreadLocalPointer
{
public:
ThreadLocalPointer() : slot_()
{
internal::ThreadLocalPlatform::AllocateSlot(slot_);
}
~ThreadLocalPointer()
{
internal::ThreadLocalPlatform::FreeSlot(slot_);
}
Type* Get()
{
return static_cast<Type*>(internal::ThreadLocalPlatform::GetValueFromSlot(slot_));
}
void Set(Type *ptr)
{
internal::ThreadLocalPlatform::SetValueInSlot(slot_, ptr);
}
private:
typedef internal::ThreadLocalPlatform::SlotType SlotType;
SlotType slot_;
DISALLOW_COPY_AND_ASSIGN(ThreadLocalPointer);
};
class ThreadLocalBoolean
{
public:
ThreadLocalBoolean() {}
~ThreadLocalBoolean() {}
bool Get()
{
return !!tlp_.Get();
}
void Set(bool val)
{
tlp_.Set(reinterpret_cast<void*>(val ? 1 : 0));
}
private:
ThreadLocalPointer<void> tlp_;
DISALLOW_COPY_AND_ASSIGN(ThreadLocalBoolean);
};
} // namespace nbase
#endif // BASE_THREAD_THREAD_LOCAL_H_
@@ -0,0 +1,48 @@
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: wrt(guangguang)
// Date: 2011/6/14
//
// This file implements some useful thread local template data structures for Posix
#include "base/thread/thread_local.h"
#if defined(OS_POSIX)
#include <assert.h>
#include <pthread.h>
namespace nbase {
namespace internal {
// static
void ThreadLocalPlatform::AllocateSlot(SlotType &slot)
{
int error = pthread_key_create(&slot, NULL);
assert(error == 0);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType &slot)
{
int error = pthread_key_delete(slot);
assert(error == 0);
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType &slot)
{
return pthread_getspecific(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType &slot, void *value)
{
int error = pthread_setspecific(slot, value);
assert(error == 0);
}
} // namespace internal
} // namespace base
#endif // OS_POSIX
@@ -0,0 +1,54 @@
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: wrt(guangguang)
// Date: 2011/6/14
//
// This file implements some useful thread local template data structures for Windows
#include "base/thread/thread_local.h"
#if defined(OS_WIN)
#include <assert.h>
#include <windows.h>
namespace nbase
{
namespace internal
{
// static
void ThreadLocalPlatform::AllocateSlot(SlotType &slot)
{
slot = ::TlsAlloc();
assert(slot != TLS_OUT_OF_INDEXES);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType &slot)
{
if (!::TlsFree(slot))
{
assert(false);
}
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType &slot)
{
return ::TlsGetValue(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType &slot, void *value)
{
if (!::TlsSetValue(slot, value))
{
assert(false);
}
}
} // namespace internal
} // namespace base
#endif // OS_WIN
@@ -0,0 +1,256 @@
// Copyright (c) 2012, NetEase Inc. All rights reserved.
//
// wrt(guangguang)
// 2012/2/22
//
// a thread manager for iter-thread communicatios, etc.
#include "thread_manager.h"
#include "base/framework/message_loop.h"
//#include "base/log/log.h"
#include "base/memory/singleton.h"
#include "base/third_party/chrome/atomicops.h"
#define AUTO_MAP_LOCK() NAutoLock __l(&GetInstance()->lock_);
#define AQUIRE_ACCESS() {if (!AquireAccess()) { /*DCHECK(false);*/ return false; }}
namespace nbase
{
bool ThreadMap::AquireAccess()
{
FrameworkThreadTlsData *tls = FrameworkThread::GetTlsData();
if (!tls || tls->managed < 1)
return false;
return true;
}
bool ThreadMap::RegisterThread(int self_identifier)
{
//DCHECK(self_identifier >= 0);
if (self_identifier < 0)
return false;
FrameworkThreadTlsData *tls = FrameworkThread::GetTlsData();
//DCHECK(tls); // should be called by a Framework thread
if (tls == NULL)
return false;
AUTO_MAP_LOCK()
std::pair<std::map<int, FrameworkThread*>::iterator, bool> pr =
ThreadMap::GetInstance()->threads_.insert(
std::make_pair(self_identifier, tls->self));
if (!pr.second)
{
if (pr.first->second != tls->self)
{
//DCHECK(false); // another thread has registered with the same id
return false;
}
// yes, it's me, check logic error
//DCHECK(tls->managed > 0);
//DCHECK(tls->managed_thread_id == self_identifier);
}
// 'self' is registered
tls->managed++;
tls->managed_thread_id = self_identifier;
return true;
}
bool ThreadMap::UnregisterThread()
{
FrameworkThreadTlsData *tls = FrameworkThread::GetTlsData();
//DCHECK(tls); // should be called by a Framework thread
//DCHECK(tls->managed > 0); // should be managed
if (!tls || tls->managed < 1)
return false;
// remove from internal thread map
// here, since tls->managed is greater than zero,
// we must have a reference of the glabal ThreadManager instance (see RegisterThread)
if (--tls->managed == 0)
{
AUTO_MAP_LOCK()
std::map<int, FrameworkThread*>::iterator iter = GetInstance()->threads_.find(tls->managed_thread_id);
if (iter != GetInstance()->threads_.end())
GetInstance()->threads_.erase(iter);
else {}
//DCHECK(false); // logic error, we should not come here
tls->managed_thread_id = -1;
}
return true;
}
// no lock
FrameworkThread* ThreadMap::QueryThreadInternal(int identifier) const
{
std::map<int, FrameworkThread*>::iterator iter
= GetInstance()->threads_.find(identifier);
if (iter == GetInstance()->threads_.end())
return NULL;
return iter->second;
}
int ThreadMap::QueryThreadId(const FrameworkThread *thread)
{
AQUIRE_ACCESS()
AUTO_MAP_LOCK()
std::map<int, FrameworkThread*>::iterator iter;
for (iter = GetInstance()->threads_.begin();
iter != GetInstance()->threads_.end(); iter++) {
if (iter->second == thread)
return iter->first;
}
return -1;
}
std::shared_ptr<MessageLoopProxy> ThreadMap::GetMessageLoop(int identifier) const
{
FrameworkThread *thread = QueryThreadInternal(identifier);
if (thread == NULL)
return NULL;
MessageLoop *message_loop = thread->message_loop();
if (message_loop == NULL)
return NULL;
return message_loop->message_loop_proxy();
}
bool ThreadManager::RegisterThread(int self_identifier)
{
return ThreadMap::GetInstance()->RegisterThread(self_identifier);
}
bool ThreadManager::UnregisterThread()
{
return ThreadMap::GetInstance()->UnregisterThread();
}
int ThreadManager::QueryThreadId(const FrameworkThread *thread)
{
return ThreadMap::GetInstance()->QueryThreadId(thread);
}
FrameworkThread* ThreadManager::CurrentThread()
{
FrameworkThreadTlsData *tls = FrameworkThread::GetTlsData();
//DCHECK(tls); // should be called by a Framework thread
//DCHECK(tls->managed > 0); // should be managed
if (!tls || tls->managed < 1)
return NULL;
return tls->self;
}
bool ThreadManager::PostTask(const StdClosure &task)
{
MessageLoop::current()->PostTask(task);
return true;
}
bool ThreadManager::PostTask(int identifier, const StdClosure &task)
{
std::shared_ptr<MessageLoopProxy> message_loop =
ThreadMap::GetInstance()->GetMessageLoop(identifier);
if (message_loop == NULL)
return false;
message_loop->PostTask(task);
return true;
}
bool ThreadManager::PostDelayedTask(const StdClosure &task, TimeDelta delay)
{
MessageLoop::current()->PostDelayedTask(task, delay);
return true;
}
bool ThreadManager::PostDelayedTask(int identifier, const StdClosure &task, TimeDelta delay)
{
std::shared_ptr<MessageLoopProxy> message_loop =
ThreadMap::GetInstance()->GetMessageLoop(identifier);
if (message_loop == NULL)
return false;
message_loop->PostDelayedTask(task, delay);
return true;
}
void ThreadManager::PostRepeatedTask(const WeakCallback<StdClosure>& task, const TimeDelta& delay, int times)
{
StdClosure closure = nbase::Bind(&ThreadManager::RunRepeatedly, task, delay, times);
nbase::ThreadManager::PostDelayedTask(closure, delay);
}
void ThreadManager::PostRepeatedTask(int thread_id, const WeakCallback<StdClosure>& task, const TimeDelta& delay, int times)
{
StdClosure closure = nbase::Bind(&ThreadManager::RunRepeatedly2, thread_id, task, delay, times);
nbase::ThreadManager::PostDelayedTask(thread_id, closure, delay);
}
bool ThreadManager::PostNonNestableTask(const StdClosure &task)
{
MessageLoop::current()->PostNonNestableTask(task);
return true;
}
bool ThreadManager::PostNonNestableTask(int identifier, const StdClosure &task)
{
std::shared_ptr<MessageLoopProxy> message_loop =
ThreadMap::GetInstance()->GetMessageLoop(identifier);
if (message_loop == NULL)
return false;
message_loop->PostNonNestableTask(task);
return true;
}
bool ThreadManager::PostNonNestableDelayedTask(const StdClosure &task, TimeDelta delay)
{
MessageLoop::current()->PostNonNestableDelayedTask(task, delay);
return true;
}
bool ThreadManager::PostNonNestableDelayedTask(int identifier, const StdClosure &task, TimeDelta delay)
{
std::shared_ptr<MessageLoopProxy> message_loop =
ThreadMap::GetInstance()->GetMessageLoop(identifier);
if (message_loop == NULL)
return false;
message_loop->PostNonNestableDelayedTask(task, delay);
return true;
}
void ThreadManager::RunRepeatedly(const WeakCallback<StdClosure>& task, const TimeDelta& delay, int times)
{
if (task.Expired()) {
return;
}
task();
if (task.Expired()) {
return;
}
if (times != TIMES_FOREVER) {
times--;
}
if (times != 0) {
PostRepeatedTask(task, delay, times);
}
}
void ThreadManager::RunRepeatedly2(int thread_id, const WeakCallback<StdClosure>& task, const TimeDelta& delay, int times)
{
if (task.Expired()) {
return;
}
task();
if (task.Expired()) {
return;
}
if (times != TIMES_FOREVER) {
times--;
}
if (times != 0) {
PostRepeatedTask(thread_id, task, delay, times);
}
}
}
@@ -0,0 +1,97 @@
// a thread manager for iter-thread communicatios, etc.
#ifndef BASE_THREAD_THREAD_MANAGER_H_
#define BASE_THREAD_THREAD_MANAGER_H_
#include <map>
#include <memory>
#include "base/base_export.h"
#include "base/thread/framework_thread.h"
#include "base/memory/singleton.h"
namespace nbase
{
class MessageLoop;
class MessageLoopProxy;
class ThreadMap
{
public:
SINGLETON_DEFINE(ThreadMap);
static bool AquireAccess();
bool RegisterThread(int self_identifier);
bool UnregisterThread();
int QueryThreadId(const FrameworkThread *thread);
std::shared_ptr<MessageLoopProxy> GetMessageLoop(int identifier) const;
FrameworkThread* QueryThreadInternal(int identifier) const;
private:
ThreadMap() { }
NLock lock_;
std::map<int, FrameworkThread*> threads_;
};
// 使用ThreadManager可以极大地方便线程间通信
// 注意:只有受ThreadManager托管的线程(通过Register托管)才允许调用除Register和Post族外的成员函数
class BASE_EXPORT ThreadManager
{
public:
// 托管当前FrameworkThread线程
// identifier >= 0
// 必须在self的线程过程内被调用
static bool RegisterThread(int self_identifier);
// 取消当前线程托管
// 线程运行结束之前必须调用UnregisterThread取消托管
static bool UnregisterThread();
// 查找
static FrameworkThread* CurrentThread();
template<typename T> static T* CurrentThreadT();
static int QueryThreadId(const FrameworkThread *thread);
static bool PostTask(const StdClosure &task);
static bool PostTask(int identifier, const StdClosure &task);
static bool PostDelayedTask(const StdClosure &task, TimeDelta delay);
static bool PostDelayedTask(int identifier, const StdClosure &task, TimeDelta delay);
static const int TIMES_FOREVER = -1;
static void PostRepeatedTask(const WeakCallback<StdClosure>& task, const TimeDelta& delay, int times = TIMES_FOREVER);
static void PostRepeatedTask(int thread_id, const WeakCallback<StdClosure>& task, const TimeDelta& delay, int times = TIMES_FOREVER);
static bool PostNonNestableTask(const StdClosure &task);
static bool PostNonNestableTask(int identifier, const StdClosure &task);
static bool PostNonNestableDelayedTask(const StdClosure &task, TimeDelta delay);
static bool PostNonNestableDelayedTask(int identifier, const StdClosure &task, TimeDelta delay);
template<typename T1, typename T2>
static bool Await(int identifier, const std::function<T1> &task, const std::function<T2> &reply)
{
std::shared_ptr<MessageLoopProxy> message_loop =
ThreadMap::GetInstance()->GetMessageLoop(identifier);
if (message_loop == NULL)
return false;
message_loop->PostTaskAndReply(task, reply);
return true;
}
private:
static void RunRepeatedly(const WeakCallback<StdClosure>& task, const TimeDelta& delay, int times);
static void RunRepeatedly2(int thread_id, const WeakCallback<StdClosure>& task, const TimeDelta& delay, int times);
DISALLOW_COPY_AND_ASSIGN(ThreadManager);
};
template<typename T>
T* ThreadManager::CurrentThreadT()
{
return static_cast<T *>(CurrentThread());
}
}
#endif // BASE_THREAD_THREAD_MANAGER_H_
@@ -0,0 +1,134 @@
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: rl
// Date: 2011/6/11
//
// Thread implementation on posix platform.
#include "base/thread/thread.h"
#if defined(OS_POSIX)
#include <assert.h>
#include <errno.h>
#if defined(OS_LINUX)
#include <sys/syscall.h>
#endif
namespace nbase
{
Thread::Thread()
{
thread_id_ = 0;
thread_handle_ = 0;
thread_priority_ = kThreadPriorityDefault;
}
Thread::~Thread()
{
Close();
}
bool Thread::Create()
{
// initialize the thread attribute
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
// if thread need set priority
if (thread_priority_ > kThreadPriorityDefault)
{
pthread_attr_setschedpolicy(&thread_attr, SCHED_RR);
struct sched_param param;
if (thread_priority_ == kThreadPriorityLow)
param.sched_priority = 15;
else if (thread_priority_ == kThreadPriorityNormal)
param.sched_priority = 0;
else if (thread_priority_ == kThreadPriorityHigh)
param.sched_priority = -15;
else if (thread_priority_ == kThreadPriorityRealtime)
param.sched_priority = -20;
pthread_attr_setschedparam(&thread_attr, &param);
}
if (pthread_create(&thread_handle_, &thread_attr, ThreadProcFunc, this))
{
pthread_attr_destroy(&thread_attr);
return false;
}
pthread_attr_destroy(&thread_attr);
return true;
}
void Thread::Close()
{
if (thread_handle_ != 0)
{
if (pthread_join(thread_handle_, NULL))
assert(0);
thread_handle_ = 0;
}
}
void Thread::Terminate()
{
if (thread_handle_ != 0)
{
pthread_cancel(thread_handle_);
}
}
// static
void Thread::Sleep(int duration_ms)
{
struct timespec sleep_time, remaining;
// Contains the portion of duration_ms >= 1 sec.
sleep_time.tv_sec = duration_ms / 1000;
duration_ms -= sleep_time.tv_sec * 1000;
// Contains the portion of duration_ms < 1 sec.
sleep_time.tv_nsec = duration_ms * 1000 * 1000; // nanoseconds.
while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
sleep_time = remaining;
}
// static
void Thread::YieldThread()
{
sched_yield();
}
// static
ThreadId Thread::CurrentId()
{
#if defined(OS_LINUX)
return syscall(_NR_gettid);
#elif defined(OS_FREEBSD)
return reinterpret_cast<int64_t> (pthread_self());
#else
return reinterpret_cast<int64_t> (pthread_self());
#endif
}
void* Thread::ThreadProcFunc(void *arg)
{
Thread* the_thread = (Thread*)arg;
assert(the_thread);
if (the_thread != NULL)
{
the_thread->Run();
}
return NULL;
}
} // namespace nbase
#endif // OS_POSIX
@@ -0,0 +1,157 @@
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: rl
// Date: 2011/6/11
//
// Thread implementation on windows platform.
#include "base/thread/thread.h"
#if defined(OS_WIN)
#include <assert.h>
namespace nbase
{
// Set a Thread Name in Native Code
// http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
#if defined(OS_WIN) && defined(COMPILER_MSVC)
const DWORD MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
// Note that the thread name is copied to the thread so that the memory for the
// threadName parameter can be released.
void SetThreadName(DWORD thread_id, const char* name)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = thread_id;
info.dwFlags = 0;
__try {
RaiseException(MS_VC_EXCEPTION,
0,
sizeof(info)/sizeof(ULONG_PTR),
(ULONG_PTR*)&info);
} __except(EXCEPTION_EXECUTE_HANDLER) {
//
}
}
#endif
Thread::Thread()
{
thread_id_ = 0;
thread_handle_ = NULL;
thread_priority_ = kThreadPriorityDefault;
}
Thread::~Thread()
{
Close();
}
bool Thread::Create()
{
// create thread first
thread_handle_ = (HANDLE)_beginthreadex(NULL,
0, ThreadProcFunc, this, 0, (unsigned*)&thread_id_);
if (thread_handle_ < (HANDLE)2)
{
thread_handle_ = NULL;
thread_id_ = 0;
}
// if thread need set priority
if (thread_priority_ > kThreadPriorityDefault)
{
// set the thread priority
int pri = THREAD_PRIORITY_BELOW_NORMAL;
if (thread_priority_ == kThreadPriorityLow)
pri = THREAD_PRIORITY_LOWEST;
else if (thread_priority_ == kThreadPriorityNormal)
pri = THREAD_PRIORITY_BELOW_NORMAL;
else if (thread_priority_ == kThreadPriorityHigh)
pri = THREAD_PRIORITY_HIGHEST;
else if (thread_priority_ == kThreadPriorityRealtime)
pri = THREAD_PRIORITY_TIME_CRITICAL;
SetThreadPriority (thread_handle_, pri);
}
return thread_handle_ > (HANDLE)1;
}
void Thread::Close()
{
if (thread_handle_)
{
if (WAIT_OBJECT_0 == WaitForSingleObject(thread_handle_, INFINITE))
{
::CloseHandle(thread_handle_);
thread_handle_ = NULL;
thread_id_ = 0;
}
else
{
Terminate();
}
}
}
void Thread::Terminate()
{
if (thread_handle_)
{
::TerminateThread(thread_handle_, 0);
::CloseHandle(thread_handle_);
thread_handle_ = NULL;
thread_id_ = 0;
}
}
// static
void Thread::Sleep(int duration_ms)
{
::Sleep(duration_ms);
}
// static
void Thread::YieldThread()
{
::Sleep(0);
}
// static
ThreadId Thread::CurrentId()
{
return GetCurrentThreadId();
}
uint32_t __stdcall Thread::ThreadProcFunc(void *arg)
{
Thread* the_thread = (Thread*)arg;
assert(the_thread);
if (the_thread != NULL)
{
the_thread->Run();
}
_endthreadex(0);
return 0;
}
} // namespace nbase
#endif // OS_POSIX