You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

577 lines
15 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004 Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/base/thread.h"
  28. #ifndef __has_feature
  29. #define __has_feature(x) 0 // Compatibility with non-clang or LLVM compilers.
  30. #endif // __has_feature
  31. #if defined(WIN32)
  32. #include <comdef.h>
  33. #elif defined(POSIX)
  34. #include <time.h>
  35. #endif
  36. #include "talk/base/common.h"
  37. #include "talk/base/logging.h"
  38. #include "talk/base/stringutils.h"
  39. #include "talk/base/timeutils.h"
  40. #if !__has_feature(objc_arc) && (defined(OSX) || defined(IOS))
  41. #include "talk/base/maccocoathreadhelper.h"
  42. #include "talk/base/scoped_autorelease_pool.h"
  43. #endif
  44. namespace talk_base {
  45. ThreadManager* ThreadManager::Instance() {
  46. LIBJINGLE_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
  47. return &thread_manager;
  48. }
  49. #ifdef POSIX
  50. ThreadManager::ThreadManager() {
  51. pthread_key_create(&key_, NULL);
  52. #ifndef NO_MAIN_THREAD_WRAPPING
  53. WrapCurrentThread();
  54. #endif
  55. #if !__has_feature(objc_arc) && (defined(OSX) || defined(IOS))
  56. // Under Automatic Reference Counting (ARC), you cannot use autorelease pools
  57. // directly. Instead, you use @autoreleasepool blocks instead. Also, we are
  58. // maintaining thread safety using immutability within context of GCD dispatch
  59. // queues in this case.
  60. InitCocoaMultiThreading();
  61. #endif
  62. }
  63. ThreadManager::~ThreadManager() {
  64. #if __has_feature(objc_arc)
  65. @autoreleasepool
  66. #elif defined(OSX) || defined(IOS)
  67. // This is called during exit, at which point apparently no NSAutoreleasePools
  68. // are available; but we might still need them to do cleanup (or we get the
  69. // "no autoreleasepool in place, just leaking" warning when exiting).
  70. ScopedAutoreleasePool pool;
  71. #endif
  72. {
  73. UnwrapCurrentThread();
  74. pthread_key_delete(key_);
  75. }
  76. }
  77. Thread *ThreadManager::CurrentThread() {
  78. return static_cast<Thread *>(pthread_getspecific(key_));
  79. }
  80. void ThreadManager::SetCurrentThread(Thread *thread) {
  81. pthread_setspecific(key_, thread);
  82. }
  83. #endif
  84. #ifdef WIN32
  85. ThreadManager::ThreadManager() {
  86. key_ = TlsAlloc();
  87. #ifndef NO_MAIN_THREAD_WRAPPING
  88. WrapCurrentThread();
  89. #endif
  90. }
  91. ThreadManager::~ThreadManager() {
  92. UnwrapCurrentThread();
  93. TlsFree(key_);
  94. }
  95. Thread *ThreadManager::CurrentThread() {
  96. return static_cast<Thread *>(TlsGetValue(key_));
  97. }
  98. void ThreadManager::SetCurrentThread(Thread *thread) {
  99. TlsSetValue(key_, thread);
  100. }
  101. #endif
  102. // static
  103. Thread *ThreadManager::WrapCurrentThread() {
  104. Thread* result = CurrentThread();
  105. if (NULL == result) {
  106. result = new Thread();
  107. result->WrapCurrentWithThreadManager(this);
  108. }
  109. return result;
  110. }
  111. // static
  112. void ThreadManager::UnwrapCurrentThread() {
  113. Thread* t = CurrentThread();
  114. if (t && !(t->IsOwned())) {
  115. t->UnwrapCurrent();
  116. delete t;
  117. }
  118. }
  119. struct ThreadInit {
  120. Thread* thread;
  121. Runnable* runnable;
  122. };
  123. Thread::Thread(SocketServer* ss)
  124. : MessageQueue(ss),
  125. priority_(PRIORITY_NORMAL),
  126. started_(false),
  127. has_sends_(false),
  128. #if defined(WIN32)
  129. thread_(NULL),
  130. thread_id_(0),
  131. #endif
  132. owned_(true),
  133. delete_self_when_complete_(false) {
  134. SetName("Thread", this); // default name
  135. }
  136. Thread::~Thread() {
  137. Stop();
  138. if (active_)
  139. Clear(NULL);
  140. }
  141. bool Thread::SleepMs(int milliseconds) {
  142. #ifdef WIN32
  143. ::Sleep(milliseconds);
  144. return true;
  145. #else
  146. // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
  147. // so we use nanosleep() even though it has greater precision than necessary.
  148. struct timespec ts;
  149. ts.tv_sec = milliseconds / 1000;
  150. ts.tv_nsec = (milliseconds % 1000) * 1000000;
  151. int ret = nanosleep(&ts, NULL);
  152. if (ret != 0) {
  153. LOG_ERR(LS_WARNING) << "nanosleep() returning early";
  154. return false;
  155. }
  156. return true;
  157. #endif
  158. }
  159. bool Thread::SetName(const std::string& name, const void* obj) {
  160. if (started_) return false;
  161. name_ = name;
  162. if (obj) {
  163. char buf[16];
  164. sprintfn(buf, sizeof(buf), " 0x%p", obj);
  165. name_ += buf;
  166. }
  167. return true;
  168. }
  169. bool Thread::SetPriority(ThreadPriority priority) {
  170. #if defined(WIN32)
  171. if (started_) {
  172. BOOL ret = FALSE;
  173. if (priority == PRIORITY_NORMAL) {
  174. ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_NORMAL);
  175. } else if (priority == PRIORITY_HIGH) {
  176. ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_HIGHEST);
  177. } else if (priority == PRIORITY_ABOVE_NORMAL) {
  178. ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);
  179. } else if (priority == PRIORITY_IDLE) {
  180. ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_IDLE);
  181. }
  182. if (!ret) {
  183. return false;
  184. }
  185. }
  186. priority_ = priority;
  187. return true;
  188. #else
  189. // TODO: Implement for Linux/Mac if possible.
  190. if (started_) return false;
  191. priority_ = priority;
  192. return true;
  193. #endif
  194. }
  195. bool Thread::Start(Runnable* runnable) {
  196. ASSERT(owned_);
  197. if (!owned_) return false;
  198. ASSERT(!started_);
  199. if (started_) return false;
  200. // Make sure that ThreadManager is created on the main thread before
  201. // we start a new thread.
  202. ThreadManager::Instance();
  203. ThreadInit* init = new ThreadInit;
  204. init->thread = this;
  205. init->runnable = runnable;
  206. #if defined(WIN32)
  207. DWORD flags = 0;
  208. if (priority_ != PRIORITY_NORMAL) {
  209. flags = CREATE_SUSPENDED;
  210. }
  211. thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, flags,
  212. &thread_id_);
  213. if (thread_) {
  214. started_ = true;
  215. if (priority_ != PRIORITY_NORMAL) {
  216. SetPriority(priority_);
  217. ::ResumeThread(thread_);
  218. }
  219. } else {
  220. return false;
  221. }
  222. #elif defined(POSIX)
  223. pthread_attr_t attr;
  224. pthread_attr_init(&attr);
  225. if (priority_ != PRIORITY_NORMAL) {
  226. if (priority_ == PRIORITY_IDLE) {
  227. // There is no POSIX-standard way to set a below-normal priority for an
  228. // individual thread (only whole process), so let's not support it.
  229. LOG(LS_WARNING) << "PRIORITY_IDLE not supported";
  230. } else {
  231. // Set real-time round-robin policy.
  232. if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) {
  233. LOG(LS_ERROR) << "pthread_attr_setschedpolicy";
  234. }
  235. struct sched_param param;
  236. if (pthread_attr_getschedparam(&attr, &param) != 0) {
  237. LOG(LS_ERROR) << "pthread_attr_getschedparam";
  238. } else {
  239. // The numbers here are arbitrary.
  240. if (priority_ == PRIORITY_HIGH) {
  241. param.sched_priority = 6; // 6 = HIGH
  242. } else {
  243. ASSERT(priority_ == PRIORITY_ABOVE_NORMAL);
  244. param.sched_priority = 4; // 4 = ABOVE_NORMAL
  245. }
  246. if (pthread_attr_setschedparam(&attr, &param) != 0) {
  247. LOG(LS_ERROR) << "pthread_attr_setschedparam";
  248. }
  249. }
  250. }
  251. }
  252. int error_code = pthread_create(&thread_, &attr, PreRun, init);
  253. if (0 != error_code) {
  254. LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
  255. return false;
  256. }
  257. started_ = true;
  258. #endif
  259. return true;
  260. }
  261. void Thread::Join() {
  262. if (started_) {
  263. ASSERT(!IsCurrent());
  264. #if defined(WIN32)
  265. WaitForSingleObject(thread_, INFINITE);
  266. CloseHandle(thread_);
  267. thread_ = NULL;
  268. thread_id_ = 0;
  269. #elif defined(POSIX)
  270. void *pv;
  271. pthread_join(thread_, &pv);
  272. #endif
  273. started_ = false;
  274. }
  275. }
  276. #ifdef WIN32
  277. // As seen on MSDN.
  278. // http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx
  279. #define MSDEV_SET_THREAD_NAME 0x406D1388
  280. typedef struct tagTHREADNAME_INFO {
  281. DWORD dwType;
  282. LPCSTR szName;
  283. DWORD dwThreadID;
  284. DWORD dwFlags;
  285. } THREADNAME_INFO;
  286. void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) {
  287. THREADNAME_INFO info;
  288. info.dwType = 0x1000;
  289. info.szName = szThreadName;
  290. info.dwThreadID = dwThreadID;
  291. info.dwFlags = 0;
  292. __try {
  293. RaiseException(MSDEV_SET_THREAD_NAME, 0, sizeof(info) / sizeof(DWORD),
  294. reinterpret_cast<ULONG_PTR*>(&info));
  295. }
  296. __except(EXCEPTION_CONTINUE_EXECUTION) {
  297. }
  298. }
  299. #endif // WIN32
  300. void* Thread::PreRun(void* pv) {
  301. ThreadInit* init = static_cast<ThreadInit*>(pv);
  302. ThreadManager::Instance()->SetCurrentThread(init->thread);
  303. #if defined(WIN32)
  304. SetThreadName(GetCurrentThreadId(), init->thread->name_.c_str());
  305. #elif defined(POSIX)
  306. // TODO: See if naming exists for pthreads.
  307. #endif
  308. #if __has_feature(objc_arc)
  309. @autoreleasepool
  310. #elif defined(OSX) || defined(IOS)
  311. // Make sure the new thread has an autoreleasepool
  312. ScopedAutoreleasePool pool;
  313. #endif
  314. {
  315. if (init->runnable) {
  316. init->runnable->Run(init->thread);
  317. } else {
  318. init->thread->Run();
  319. }
  320. if (init->thread->delete_self_when_complete_) {
  321. init->thread->started_ = false;
  322. delete init->thread;
  323. }
  324. delete init;
  325. return NULL;
  326. }
  327. }
  328. void Thread::Run() {
  329. ProcessMessages(kForever);
  330. }
  331. bool Thread::IsOwned() {
  332. return owned_;
  333. }
  334. void Thread::Stop() {
  335. MessageQueue::Quit();
  336. Join();
  337. }
  338. void Thread::Send(MessageHandler *phandler, uint32 id, MessageData *pdata) {
  339. if (fStop_)
  340. return;
  341. // Sent messages are sent to the MessageHandler directly, in the context
  342. // of "thread", like Win32 SendMessage. If in the right context,
  343. // call the handler directly.
  344. Message msg;
  345. msg.phandler = phandler;
  346. msg.message_id = id;
  347. msg.pdata = pdata;
  348. if (IsCurrent()) {
  349. phandler->OnMessage(&msg);
  350. return;
  351. }
  352. AutoThread thread;
  353. Thread *current_thread = Thread::Current();
  354. ASSERT(current_thread != NULL); // AutoThread ensures this
  355. bool ready = false;
  356. {
  357. CritScope cs(&crit_);
  358. EnsureActive();
  359. _SendMessage smsg;
  360. smsg.thread = current_thread;
  361. smsg.msg = msg;
  362. smsg.ready = &ready;
  363. sendlist_.push_back(smsg);
  364. has_sends_ = true;
  365. }
  366. // Wait for a reply
  367. ss_->WakeUp();
  368. bool waited = false;
  369. while (!ready) {
  370. current_thread->ReceiveSends();
  371. current_thread->socketserver()->Wait(kForever, false);
  372. waited = true;
  373. }
  374. // Our Wait loop above may have consumed some WakeUp events for this
  375. // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
  376. // cause problems for some SocketServers.
  377. //
  378. // Concrete example:
  379. // Win32SocketServer on thread A calls Send on thread B. While processing the
  380. // message, thread B Posts a message to A. We consume the wakeup for that
  381. // Post while waiting for the Send to complete, which means that when we exit
  382. // this loop, we need to issue another WakeUp, or else the Posted message
  383. // won't be processed in a timely manner.
  384. if (waited) {
  385. current_thread->socketserver()->WakeUp();
  386. }
  387. }
  388. void Thread::ReceiveSends() {
  389. // Before entering critical section, check boolean.
  390. if (!has_sends_)
  391. return;
  392. // Receive a sent message. Cleanup scenarios:
  393. // - thread sending exits: We don't allow this, since thread can exit
  394. // only via Join, so Send must complete.
  395. // - thread receiving exits: Wakeup/set ready in Thread::Clear()
  396. // - object target cleared: Wakeup/set ready in Thread::Clear()
  397. crit_.Enter();
  398. while (!sendlist_.empty()) {
  399. _SendMessage smsg = sendlist_.front();
  400. sendlist_.pop_front();
  401. crit_.Leave();
  402. smsg.msg.phandler->OnMessage(&smsg.msg);
  403. crit_.Enter();
  404. *smsg.ready = true;
  405. smsg.thread->socketserver()->WakeUp();
  406. }
  407. has_sends_ = false;
  408. crit_.Leave();
  409. }
  410. void Thread::Clear(MessageHandler *phandler, uint32 id,
  411. MessageList* removed) {
  412. CritScope cs(&crit_);
  413. // Remove messages on sendlist_ with phandler
  414. // Object target cleared: remove from send list, wakeup/set ready
  415. // if sender not NULL.
  416. std::list<_SendMessage>::iterator iter = sendlist_.begin();
  417. while (iter != sendlist_.end()) {
  418. _SendMessage smsg = *iter;
  419. if (smsg.msg.Match(phandler, id)) {
  420. if (removed) {
  421. removed->push_back(smsg.msg);
  422. } else {
  423. delete smsg.msg.pdata;
  424. }
  425. iter = sendlist_.erase(iter);
  426. *smsg.ready = true;
  427. smsg.thread->socketserver()->WakeUp();
  428. continue;
  429. }
  430. ++iter;
  431. }
  432. MessageQueue::Clear(phandler, id, removed);
  433. }
  434. bool Thread::ProcessMessages(int cmsLoop) {
  435. uint32 msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
  436. int cmsNext = cmsLoop;
  437. while (true) {
  438. #if __has_feature(objc_arc)
  439. @autoreleasepool
  440. #elif defined(OSX) || defined(IOS)
  441. // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
  442. // Each thread is supposed to have an autorelease pool. Also for event loops
  443. // like this, autorelease pool needs to be created and drained/released
  444. // for each cycle.
  445. ScopedAutoreleasePool pool;
  446. #endif
  447. {
  448. Message msg;
  449. if (!Get(&msg, cmsNext))
  450. return !IsQuitting();
  451. Dispatch(&msg);
  452. if (cmsLoop != kForever) {
  453. cmsNext = TimeUntil(msEnd);
  454. if (cmsNext < 0)
  455. return true;
  456. }
  457. }
  458. }
  459. }
  460. bool Thread::WrapCurrent() {
  461. return WrapCurrentWithThreadManager(ThreadManager::Instance());
  462. }
  463. bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager) {
  464. if (started_)
  465. return false;
  466. #if defined(WIN32)
  467. // We explicitly ask for no rights other than synchronization.
  468. // This gives us the best chance of succeeding.
  469. thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
  470. if (!thread_) {
  471. LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
  472. return false;
  473. }
  474. thread_id_ = GetCurrentThreadId();
  475. #elif defined(POSIX)
  476. thread_ = pthread_self();
  477. #endif
  478. owned_ = false;
  479. started_ = true;
  480. thread_manager->SetCurrentThread(this);
  481. return true;
  482. }
  483. void Thread::UnwrapCurrent() {
  484. // Clears the platform-specific thread-specific storage.
  485. ThreadManager::Instance()->SetCurrentThread(NULL);
  486. #ifdef WIN32
  487. if (!CloseHandle(thread_)) {
  488. LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
  489. }
  490. #endif
  491. started_ = false;
  492. }
  493. AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
  494. if (!ThreadManager::Instance()->CurrentThread()) {
  495. ThreadManager::Instance()->SetCurrentThread(this);
  496. }
  497. }
  498. AutoThread::~AutoThread() {
  499. if (ThreadManager::Instance()->CurrentThread() == this) {
  500. ThreadManager::Instance()->SetCurrentThread(NULL);
  501. }
  502. }
  503. #ifdef WIN32
  504. void ComThread::Run() {
  505. HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  506. ASSERT(SUCCEEDED(hr));
  507. if (SUCCEEDED(hr)) {
  508. Thread::Run();
  509. CoUninitialize();
  510. } else {
  511. LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
  512. }
  513. }
  514. #endif
  515. } // namespace talk_base