1 //===-- ThreadCollection.cpp ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 #include <stdlib.h>
10 
11 #include <algorithm>
12 #include <mutex>
13 
14 #include "lldb/Target/ThreadCollection.h"
15 #include "lldb/Target/Thread.h"
16 
17 using namespace lldb;
18 using namespace lldb_private;
19 
20 ThreadCollection::ThreadCollection() :
21     m_threads(),
22     m_mutex()
23 {
24 }
25 
26 ThreadCollection::ThreadCollection(collection threads) :
27     m_threads(threads),
28     m_mutex()
29 {
30 }
31 
32 void
33 ThreadCollection::AddThread (const ThreadSP &thread_sp)
34 {
35     std::lock_guard<std::recursive_mutex> guard(GetMutex());
36     m_threads.push_back (thread_sp);
37 }
38 
39 void
40 ThreadCollection::AddThreadSortedByIndexID (const ThreadSP &thread_sp)
41 {
42     std::lock_guard<std::recursive_mutex> guard(GetMutex());
43     // Make sure we always keep the threads sorted by thread index ID
44     const uint32_t thread_index_id = thread_sp->GetIndexID();
45     if (m_threads.empty() || m_threads.back()->GetIndexID() < thread_index_id)
46         m_threads.push_back (thread_sp);
47     else
48     {
49         m_threads.insert(std::upper_bound(m_threads.begin(), m_threads.end(), thread_sp,
50                                           [] (const ThreadSP &lhs, const ThreadSP &rhs) -> bool
51                                           {
52                                               return lhs->GetIndexID() < rhs->GetIndexID();
53                                           }), thread_sp);
54     }
55 }
56 
57 void
58 ThreadCollection::InsertThread (const lldb::ThreadSP &thread_sp, uint32_t idx)
59 {
60     std::lock_guard<std::recursive_mutex> guard(GetMutex());
61     if (idx < m_threads.size())
62         m_threads.insert(m_threads.begin() + idx, thread_sp);
63     else
64         m_threads.push_back (thread_sp);
65 }
66 
67 uint32_t
68 ThreadCollection::GetSize ()
69 {
70     std::lock_guard<std::recursive_mutex> guard(GetMutex());
71     return m_threads.size();
72 }
73 
74 ThreadSP
75 ThreadCollection::GetThreadAtIndex (uint32_t idx)
76 {
77     std::lock_guard<std::recursive_mutex> guard(GetMutex());
78     ThreadSP thread_sp;
79     if (idx < m_threads.size())
80         thread_sp = m_threads[idx];
81     return thread_sp;
82 }
83