Found 218031 results in 31780 files, showing top 50 files (show more).
github.com/html5rocks/www.html5rocks.com:static/demos/lemdoodle/examples/lem-planes/combined.js: [ master, ]
5051:   'needle': ['intro-finale/items-needle-thread', 'intro-finale/items-needle'],
5086:   'thread': ['intro-finale/items-thread', 'intro-finale/items-thread'],
5084:   'thread-thimble': ['intro-finale/items-thread-thimble',
5085:                      'intro-finale/items-thread-thimble'],
5102:     'needle', 'halo', 'noodles', 'neutron', 'nose'
5105:     'thread', 'pinstripe', 'neutron', 'noodles', 'clove'
5125:     'thread', 'thimble', 'earmuffs', 'neutron', 'nose'
5131:     'thread', 'thimble', 'noodles', 'neutron', 'nose', 'gnocchi', 'rivet',
13797:     'intro-finale/items-needle-thread',
13798:     'intro-finale/items-needle',
13839:     'intro-finale/items-thread-thimble',
13840:     'intro-finale/items-thread',
15100:   'intro-finale/items-needle-thread': { width: 68, height: 65, x: 834, y: 0 },
15101:   'intro-finale/items-needle': { top: 8, width: 59, height: 51, x: 904, y: 0 },
15142:   'intro-finale/items-thread-thimble': { left: 2, top: 11, bottom: 14, right: 11, width: 52, height: 40, x: 690, y: 96 },
15143:   'intro-finale/items-thread': { left: 4, top: 16, bottom: 15, right: 13, width: 48, height: 34, x: 744, y: 96 },
github.com/html5rocks/www.html5rocks.com:static/demos/lemdoodle/examples/lem-embedded/combined.js: [ master, ]
5024:   'needle': ['intro-finale/items-needle-thread', 'intro-finale/items-needle'],
5059:   'thread': ['intro-finale/items-thread', 'intro-finale/items-thread'],
5057:   'thread-thimble': ['intro-finale/items-thread-thimble',
5058:                      'intro-finale/items-thread-thimble'],
5075:     'needle', 'halo', 'noodles', 'neutron', 'nose'
5078:     'thread', 'pinstripe', 'neutron', 'noodles', 'clove'
5098:     'thread', 'thimble', 'earmuffs', 'neutron', 'nose'
5104:     'thread', 'thimble', 'noodles', 'neutron', 'nose', 'gnocchi', 'rivet',
13827:               // First run: Thread + thimble
13828:               nItems = ['thread', 'thimble'];
13831:               // Second run: Thread/thimble + random item that’s neither
13832:               nItems[0] = 'thread-thimble';
13836:               } while ((nItems[1] == 'thread-thimble') ||
13837:                        (nItems[1] == 'thread') || (nItems[1] == 'thimble'));
13843:             nItems = ['needle', 'noodles'];
13849:               nItems = ['thread', 'thimble'];
13852:               nItems = ['thread-thimble', 'forget-me-not'];
13859:               nItems = ['thread', 'thimble'];
13862:               nItems = ['thread-thimble', 'scissors'];
13868:             nItems = ['thread', 'pinstripe'];
13884:               nItems = ['thread', 'thimble'];
13887:               nItems = ['thread-thimble', 'neutron'];
13894:               nItems = ['thread', 'thimble'];
13897:               nItems = ['thread-thimble', 'basket'];
15362:     'intro-finale/items-needle-thread',
15363:     'intro-finale/items-needle',
15404:     'intro-finale/items-thread-thimble',
15405:     'intro-finale/items-thread',
16665:   'intro-finale/items-needle-thread': { width: 68, height: 65, x: 834, y: 0 },
16666:   'intro-finale/items-needle': { top: 8, width: 59, height: 51, x: 904, y: 0 },
16707:   'intro-finale/items-thread-thimble': { left: 2, top: 11, bottom: 14, right: 11, width: 52, height: 40, x: 690, y: 96 },
16708:   'intro-finale/items-thread': { left: 4, top: 16, bottom: 15, right: 13, width: 48, height: 34, x: 744, y: 96 },
chromium.googlesource.com/ios-chromium-mirror:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ master, ]
185:   DWORD thread;			/* Win32 thread ID */
502:   ptw32_thread_t * thread;
158:   HANDLE threadH;		/* Win32 thread handle - POSIX thread is invalid if threadH == 0 */
162:   ptw32_mcs_lock_t threadLock;	/* Used for serialised access to public thread state */
246:   pthread_t ownerThread;
346:   void *threads;
350: typedef struct ThreadParms ThreadParms;
352: struct ThreadParms
401: typedef struct ThreadKeyAssoc ThreadKeyAssoc;
403: struct ThreadKeyAssoc
505:   ThreadKeyAssoc *nextThread;
507:   ThreadKeyAssoc *prevThread;
152: typedef struct ptw32_thread_t_       ptw32_thread_t;
155: struct ptw32_thread_t_
575: #define PTW32_THREAD_REUSE_EMPTY ((ptw32_thread_t *)(size_t) 1)
198: struct pthread_attr_t_
234: struct pthread_mutex_t_
273: struct pthread_mutexattr_t_
302: struct pthread_spinlock_t_
326: struct pthread_barrier_t_
336: struct pthread_barrierattr_t_
341: struct pthread_key_t_
360: struct pthread_cond_t_
378: struct pthread_condattr_t_
385: struct pthread_rwlock_t_
396: struct pthread_rwlockattr_t_
133:   PThreadStateInitial = 0,	/* Thread not running                   */
134:   PThreadStateRunning,		/* Thread alive & kicking               */
135:   PThreadStateSuspended,	/* Thread alive but suspended           */
136:   PThreadStateCancelPending,	/* Thread alive but                     */
138:   PThreadStateCanceling,	/* Thread alive but is                  */
141:   PThreadStateExiting,		/* Thread alive but exiting             */
143:   PThreadStateLast,             /* All handlers have been run and now   */
145:   PThreadStateReuse             /* In reuse pool.                       */
147: PThreadState;
944: #define _beginthreadex(security, \
957: #define _endthreadex ExitThread
129:    * This enumeration represents the state of the thread;
130:    * The thread is still "alive" if the numeric value of the
157:   unsigned __int64 seqNumber;	/* Process-unique thread sequence number */
159:   pthread_t ptHandle;		/* This thread's permanent pthread_t handle */
160:   ptw32_thread_t * prevReuse;	/* Links threads on reuse stack */
242:   int recursive_count;		/* Number of unlocks a thread needs to perform
263:  * Node used to manage per-thread lists of currently-held robust mutexes.
407:    *      This structure creates an association between a thread and a key.
409:    *      destroy routine for thread specific data registered by a user upon
410:    *      exiting a thread.
416:    *         T - Thread that has called pthread_setspecific(Kn)
417:    *            (head of chain is thread->keys)
436:    *      general lock (guarding the row) and the thread's general
440:    *      until both the key is deleted and the thread has called the
442:    *      to be freed as soon as either thread or key is concluded.
445:    *      key and thread locks are acquired consistently in the order
446:    *      "key lock then thread lock". An exception to this exists
447:    *      when a thread calls the destructors, however, this is done
450:    *      An association is created when a thread first calls
455:    *      thread calls the key destructor function on thread exit, or
459:    *      thread
460:    *              reference to the thread that owns the
462:    *              thread struct itself. Since the association is
463:    *              destroyed before the thread exits, this can never
464:    *              point to a different logical thread to the one that
465:    *              created the assoc, i.e. after thread struct reuse.
492:    *      1)      As soon as either the key or the thread is no longer
574: /* Thread Reuse stack bottom marker. Must not be NULL or any valid pointer to memory. */
578: extern ptw32_thread_t * ptw32_threadReuseTop;
579: extern ptw32_thread_t * ptw32_threadReuseBottom;
593: extern ptw32_mcs_lock_t ptw32_thread_reuse_lock;
626:   void ptw32_robust_mutex_remove(pthread_mutex_t* mutex, ptw32_thread_t* otp);
644:   void ptw32_threadReusePush (pthread_t thread);
648:   int ptw32_setthreadpriority (pthread_t thread, int policy, int priority);
659:   void ptw32_callUserDestroyRoutines (pthread_t thread);
661:   int ptw32_tkAssocCreate (ptw32_thread_t * thread, pthread_key_t key);
6:  * Keeps all the internals out of pthread.h
10:  *      Pthreads-win32 - POSIX Threads Library for Win32
224:   pthread_mutex_t lock;
248: 				   threads. */
267:   pthread_mutex_t mx;
308:     pthread_mutex_t mutex;	/* mutex if single cpu.            */
354:   pthread_t tid;
362:   long nWaitersBlocked;		/* Number of threads blocked            */
363:   long nWaitersGone;		/* Number of threads timed out          */
364:   long nWaitersToUnblock;	/* Number of threads to unblock         */
365:   sem_t semBlockQueue;		/* Queue up threads waiting for the     */
370:   pthread_mutex_t mtxUnblockLock;	/* Mutex that guards access to          */
373:   pthread_cond_t next;		/* Doubly linked list                   */
374:   pthread_cond_t prev;
387:   pthread_mutex_t mtxExclusiveAccess;
388:   pthread_mutex_t mtxSharedAccessCompleted;
389:   pthread_cond_t cndSharedAccessCompleted;
415:    *            (head of chain is key->threads)
451:    *      pthread_setspecific() on a key that has a specified
471:    *              The pthread_t->keys attribute is the head of a
474:    *              between a pthread_t and all pthread_key_t on which
475:    *              it called pthread_setspecific.
480:    *      nextThread
481:    *              The pthread_key_t->threads attribute is the head of
484:    *              relationship between a pthread_key_t and all the 
485:    *              PThreads that have called pthread_setspecific for
486:    *              this pthread_key_t.
488:    *      prevThread
497:    *              pthread_setspecific if the user provided a
503:   pthread_key_t key;
504:   ThreadKeyAssoc *nextKey;
506:   ThreadKeyAssoc *prevKey;
571: /* Declared in pthread_cancel.c */
580: extern pthread_key_t ptw32_selfThreadKey;
581: extern pthread_key_t ptw32_cleanupKey;
582: extern pthread_cond_t ptw32_cond_list_head;
583: extern pthread_cond_t ptw32_cond_list_tail;
587: extern unsigned __int64 ptw32_threadSeqNumber;
601: extern int pthread_count;
617:   int ptw32_is_attr (const pthread_attr_t * attr);
619:   int ptw32_cond_check_need_init (pthread_cond_t * cond);
620:   int ptw32_mutex_check_need_init (pthread_mutex_t * mutex);
621:   int ptw32_rwlock_check_need_init (pthread_rwlock_t * rwlock);
622:   int ptw32_spinlock_check_need_init (pthread_spinlock_t * lock);
624:   int ptw32_robust_mutex_inherit(pthread_mutex_t * mutex);
625:   void ptw32_robust_mutex_add(pthread_mutex_t* mutex, pthread_t self);
630: 			       HANDLE threadH, DWORD callback_arg);
636:   void ptw32_threadDestroy (pthread_t tid);
640:   pthread_t ptw32_new (void);
642:   pthread_t ptw32_threadReusePop (void);
657:     ptw32_threadStart (void *vthreadParms);
663:   void ptw32_tkAssocDestroy (ThreadKeyAssoc * assoc);
714:   _CRTIMP unsigned long __cdecl _beginthread (void (__cdecl *) (void *),
716:   _CRTIMP void __cdecl _endthread (void);
937: #if defined(NEED_CREATETHREAD)
940:  * Macro uses args so we can cast start_proc to LPTHREAD_START_ROUTINE
950:         CreateThread(security, \
952:                      (LPTHREAD_START_ROUTINE) start_proc, \
959: #endif				/* NEED_CREATETHREAD */
12:  *      Copyright(C) 1999,2005 Pthreads-win32 contributors
20:  *      http://sources.redhat.com/pthreads-win32/contributors.html
131:    * state is greater or equal "PThreadStateRunning".
161:   volatile PThreadState state;
483:    *              nextThreads link. This chain provides the 1 to many
717:   _CRTIMP unsigned long __cdecl _beginthreadex (void *, unsigned,
720:   _CRTIMP void __cdecl _endthreadex (unsigned);
chromium.googlesource.com/chromium/src:native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ master, ] Duplicate result
chromium.googlesource.com/arc/arc:third_party/chromium-ppapi/native_client_sdk/src/libraries/third_party/pthreads-win32/implement.h: [ master, ] Duplicate result
github.com/google/grumpy:third_party/stdlib/threading.py: [ master, ]
631: class Thread(_Verbose):
35: _start_new_thread = thread.start_new_thread
1148: current_thread = currentThread
38: ThreadError = thread.error
1071: class _MainThread(Thread):
1096: def _pickSomeNonDaemonThread():
1111: class _DummyThread(Thread):
1135: def currentThread():
1365:     class ProducerThread(Thread):
1381:     class ConsumerThread(Thread):
1: """Thread module emulating a subset of Java's threading model."""
6:     import thread
31:            'current_thread', 'enumerate', 'Event',
32:            'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
36: _allocate_lock = thread.allocate_lock
37: _get_ident = thread.get_ident
39: del thread
67:                 # Issue #4188: calling current_thread() can incur an infinite
73:                     name = "<OS thread %d>" % ident
93:     The func will be passed to sys.setprofile() for each thread, before its
103:     The func will be passed to sys.settrace() for each thread, before its run()
117:     A reentrant lock must be released by the thread that acquired it. Once a
118:     thread has acquired a reentrant lock, the same thread may acquire it again
119:     without blocking; the thread must release it once for each time it has
126:     """A reentrant lock must be released by the thread that acquired it. Once a
127:        thread has acquired a reentrant lock, the same thread may acquire it
128:        again without blocking; the thread must release it once for each time it
150:         When invoked without arguments: if this thread already owns the lock,
152:         if another thread owns the lock, block until the lock is unlocked. Once
153:         the lock is unlocked (not owned by any thread), then grab ownership, set
154:         the recursion level to one, and return. If more than one thread is
191:         by any thread), and if any other threads are blocked waiting for the
194:         locked and owned by the calling thread.
196:         Only call this method when the calling thread owns the lock. A
246:     notified by another thread.
257:        notified by another thread.
301:         # Return True if lock is owned by current_thread.
312:         If the calling thread has not acquired the lock when this method is
317:         variable in another thread, or until the optional timeout occurs. Once
376:         If the calling thread has not acquired the lock when this method is
403:         If the calling thread has not acquired the lock when this method
445:         on entry, block, waiting until some other thread has called release() to
482:         When the counter is zero on entry and another thread is waiting for it
483:         to become larger than zero again, wake up that thread.
528:         When the counter is zero on entry and another thread is waiting for it
529:         to become larger than zero again, wake up that thread.
567:         # private!  called by Thread._reset_internal_locks by _after_fork()
601:         block until another thread calls set() to set the flag to true, or until
617: # Helper to generate new thread names
619: _counter() # Consume 0 so first non-main thread has id 1.
620: def _newname(template="Thread-%d"):
623: # Active thread administration
625: _active = {}    # maps thread id to Thread object
632:     """A class that represents a thread of control.
649:         *name* is the thread name. By default, a unique name is constructed of
650:         the form "Thread-N" where N is a small decimal number.
658:         the base class constructor (Thread.__init__()) before doing anything
659:         else to the thread.
694:         return current_thread().daemon
697:         assert self.__initialized, "Thread.__init__() was not called"
710:         """Start the thread's activity.
712:         It must be called at most once per thread object. It arranges for the
713:         object's run() method to be invoked in a separate thread of control.
716:         same thread object.
720:             raise RuntimeError("thread.__init__() not called")
724:             self._note("%s.start(): starting thread", self)
728:             _start_new_thread(self.__bootstrap, ())
736:         """Method representing the thread's activity.
748:             # Avoid a refcycle if the thread is running a function with
749:             # an argument that has a member that points to the thread.
755:         # happen when a daemon thread wakes up at an unfortunate
783:                 self._note("%s.__bootstrap(): thread started", self)
805:                     print>>_sys.stderr, ("Exception in thread %s:\n%s" %
814:                             "Exception in thread " + self.name +
860:         "Remove current thread from the dict of currently running threads."
862:         # Notes about running with dummy_thread:
864:         # Must take care to not raise an exception if dummy_thread is being
866:         # dummy_threading).  dummy_thread.get_ident() always returns -1 since
867:         # there is only one thread if dummy_thread is being used.  Thus
868:         # len(_active) is always <= 1 here, and any Thread instance created
869:         # overwrites the (if any) thread currently registered in _active.
872:         # gets overwritten the instant an instance of Thread is created; both
873:         # threads return -1 from dummy_thread.get_ident() and thus have the
876:         # it gets a KeyError if another Thread instance was created.
888:                 # could try to acquire the lock again in the same thread, (in
889:                 # current_thread()), and would block.
895:         """Wait until the thread terminates.
897:         This blocks the calling thread until the thread whose join() method is
905:         thread is still alive, the join() call timed out.
908:         block until the thread terminates.
910:         A thread can be join()ed many times.
913:         thread as that would cause a deadlock. It is also an error to join() a
914:         thread before it has been started and attempts to do so raises the same
919:             raise RuntimeError("Thread.__init__() not called")
921:             raise RuntimeError("cannot join thread before it is started")
922:         if self is current_thread():
923:             raise RuntimeError("cannot join current thread")
927:                 self._note("%s.join(): waiting until thread stops", self)
934:                     self._note("%s.join(): thread stopped", self)
946:                         self._note("%s.join(): thread stopped", self)
957:         assert self.__initialized, "Thread.__init__() not called"
961:         assert self.__initialized, "Thread.__init__() not called"
968:         """Thread identifier of this thread or None if it has not been started.
970:         This is a nonzero integer. See the thread.get_ident() function. Thread
971:         identifiers may be recycled when a thread exits and another thread is
972:         created. The identifier is available even after the thread has exited.
975:         assert self.__initialized, "Thread.__init__() not called"
979:         """Return whether the thread is alive.
986:         assert self.__initialized, "Thread.__init__() not called"
992:         """A boolean value indicating whether this thread is a daemon thread (True) or not (False).
995:         raised. Its initial value is inherited from the creating thread; the
996:         main thread is not a daemon thread and therefore all threads created in
997:         the main thread default to daemon = False.
1003:         assert self.__initialized, "Thread.__init__() not called"
1008:             raise RuntimeError("Thread.__init__() not called")
1010:             raise RuntimeError("cannot set daemon status of active thread");
1041: class _Timer(Thread):
1051:         Thread.__init__(self)
1068: # Special thread class to represent the main thread
1074:         Thread.__init__(self, name="MainThread")
1103: # Dummy thread class to represent threads not started here.
1105: # If they invoke anything in threading.py that calls current_thread(), they
1107: # Their purpose is to return *something* from current_thread().
1114:         Thread.__init__(self, name=_newname("Dummy-%d"))
1116:         # Thread.__block consumes an OS-level locking primitive, which
1130:         assert False, "cannot join a dummy thread"
1136:     """Return the current Thread object, corresponding to the caller's thread of control.
1138:     If the caller's thread of control was not created through the threading
1139:     module, a dummy thread object with limited functionality is returned.
1145:         ##print "current_thread(): no current thread for", _get_ident()
1151:     """Return the number of Thread objects currently alive.
1167:     """Return a list of all Thread objects currently alive.
1169:     The list includes daemonic threads, dummy thread objects created by
1170:     current_thread(), and the main thread. It excludes terminated threads and
1177: from thread import stack_size
1179: # Create the main thread object,
1185: # get thread-local implementation, either from the thread
1188: # NOTE: Thread local classes follow: the Grumpy version of this file copies
1196:         key = '_local__key', 'thread.local.' + str(id(self))
1204:         # We need to create the thread dict in anticipation of
1208:         current_thread().__dict__[key] = dict
1214:     d = current_thread().__dict__.get(key)
1217:         current_thread().__dict__[key] = d
1279:         for thread in threads:
1281:                 __dict__ = thread.__dict__
1283:                 # Thread is dying, rest in peace.
1290:                     pass # didn't have anything in this thread
1300:     # by another (non-forked) thread.  http://bugs.python.org/issue874900
1304:     # fork() only copied the current thread; clear references to others.
1306:     current = current_thread()
1308:         for thread in _enumerate():
1311:             if hasattr(thread, '_reset_internal_locks'):
1312:                 thread._reset_internal_locks()
1313:             if thread is current:
1314:                 # There is only one active thread. We reset the ident to
1317:                 thread.__ident = ident
1318:                 new_active[ident] = thread
1321:                 thread.__stop()
1368:             Thread.__init__(self, name="Producer")
1384:             Thread.__init__(self, name="Consumer")
19: #  This threading model was originally inspired by Java, and inherited
29: # Rename some stuff so "from threading import *" is safe
30: __all__ = ['activeCount', 'active_count', 'Condition', 'currentThread',
45:                         module='threading', message='sys.exc_clear')
68:                 # recursion if it has to create a DummyThread on the fly.
91:     """Set a profile function for all threads started from the threading module.
101:     """Set a trace function for all threads started from the threading module.
245:     A condition variable allows one or more threads to wait until they are
256:     """Condition variables allow one or more threads to wait until they are
374:         """Wake up one or more threads waiting on this condition, if any.
379:         This method wakes up at most n of the threads waiting for the condition
380:         variable; it is a no-op if no threads are waiting.
401:         """Wake up all threads waiting on this condition.
449:         which blocked threads are awakened should not be relied on. There is no
579:         All threads waiting for the flag to become true are awakened. Threads
590:         Subsequently, threads calling wait() will block until set() is called to
629: # Main class for threads
643:         *group* should be None; reserved for future extension when a ThreadGroup
683:         if hasattr(self, '__block'):  # DummyThread deletes self.__block
693:         # Overridden in _MainThread and _DummyThread
722:             raise RuntimeError("threads can only be started once")
763:         # reported.  Also, we only suppress them for daemonic threads;
835:                 # test_threading.test_no_refcycle_through_target when
871:         # An instance of _MainThread is always created by 'threading'.  This
874:         # same key in the dict.  So when the _MainThread instance created by
875:         # 'threading' tries to clean itself up when atexit calls this method
879:         # _active if dummy_threading is being used is a red herring.  But
880:         # since it isn't if dummy_threading is *not* being used then don't
891:             if 'dummy_threading' not in _sys.modules:
953:         It has no semantics. Multiple threads may be given the same name. The
983:         returns a list of all alive threads.
999:         The entire Python program exits when no alive non-daemon threads are
1085:         t = _pickSomeNonDaemonThread()
1088:                 self._note("%s: waiting for other threads", self)
1091:             t = _pickSomeNonDaemonThread()
1108: # They are marked as daemon threads so we won't wait for them
1117:         # can never be used by a _DummyThread.  Since a _DummyThread
1146:         return _DummyThread()
1171:     threads that have not yet been started.
1181: # (Py_Main) as threading._shutdown.
1183: _shutdown = _MainThread()._exitfunc
1189: # these from _threading_local.py to avoid circular dependency issues.
1272:             threads = _enumerate()
1274:             # If enumerating the current threads fails, as it seems to do
1292: # END _threading_local.py copy
1296:     # is called from PyOS_AfterFork.  Here we cleanup threading module state
1401:         t = ProducerThread(Q, NI)
1404:     C = ConsumerThread(Q, NI*NP)
850:         # DummyThreads delete self.__block, but they have no waiters to
1295:     # This function is called by Python/ceval.c:PyEval_ReInitThreads which
github.com/html5rocks/slides.html5rocks.com:src/canvasphoto/utilities.js: [ master, ]
333: ...(751 bytes skipped)....subscribe(onTween);this._onComplete.subscribe(onComplete);}};YAHOO.util.AnimMgr=new function(){var thread=null;var queue=[];var tweenCount=0;this.fps=1000;this.delay=1;this.registerElement=function(tween){...(197 bytes skipped)...
83: ...(5 bytes skipped)...n id;};return Y.Dom.batch(el,f,Y.Dom,true)||f.apply(Y.Dom,arguments);},isAncestor:function(haystack,needle){haystack=Y.Dom.get(haystack);if(!haystack||!needle){return false;}
86: return false;};return Y.Dom.batch(needle,f,Y.Dom,true);},inDocument:function(el){var f=function(el){if(isSafari){while(el=el.parentNode){if(...(44 bytes skipped)...
335: return true;};this.start=function(){if(thread===null){thread=setInterval(this.run,this.delay);}};this.stop=function(tween){if(!tween){clearInterval(thread);for(var i=0,len=queue.length;i<len;++i){if(queue[0].isAnimated()){this.unRegister(queue[0],0);}}
336: queue=[];thread=null;tweenCount=0;}
android.googlesource.com/trusty/lk/common:include/kernel/thread.h: [ master, ]
87: typedef struct thread {
47: #define THREAD_STATS 1
48: #define THREAD_STACK_HIGHWATER 1
51: enum thread_state {
52:     THREAD_SUSPENDED = 0,
53:     THREAD_READY,
54:     THREAD_RUNNING,
55:     THREAD_BLOCKED,
56:     THREAD_SLEEPING,
57:     THREAD_DEATH,
60: typedef int (*thread_start_routine)(void *arg);
63: enum thread_tls_list {
76: #define THREAD_FLAG_DETACHED                  (1U<<0)
77: #define THREAD_FLAG_FREE_STACK                (1U<<1)
78: #define THREAD_FLAG_FREE_STRUCT               (1U<<2)
79: #define THREAD_FLAG_REAL_TIME                 (1U<<3)
80: #define THREAD_FLAG_IDLE                      (1U<<4)
81: #define THREAD_FLAG_DEBUG_STACK_BOUNDS_CHECK  (1U<<5)
82: #define THREAD_FLAG_EXIT_ON_PANIC             (1U<<6)
83: #define THREAD_FLAG_FREE_SHADOW_STACK         (1U<<7)
85: #define THREAD_MAGIC (0x74687264) // 'thrd'
98:     struct list_node thread_list_node;
133: } thread_t;
136: #define thread_curr_cpu(t) ((t)->curr_cpu)
137: #define thread_pinned_cpu(t) ((t)->pinned_cpu)
138: #define thread_set_curr_cpu(t,c) ((t)->curr_cpu = (c))
140: #define thread_curr_cpu(t) (0)
141: #define thread_pinned_cpu(t) (-1)
142: #define thread_set_curr_cpu(t,c) do {} while(0)
206: static inline void thread_sleep(lk_time_t delay_ms) {
235: static inline uint thread_lock_owner_get(void) {
239: static inline void thread_lock_complete(void) {
245: static inline void thread_unlock_prepare(void) {
252: #define THREAD_LOCK(state) \
257: #define THREAD_UNLOCK(state) \
261: static inline void thread_lock_ints_disabled(void) {
267: static inline void thread_unlock_ints_disabled(void) {
272: static inline bool thread_lock_held(void)
283: static inline __ALWAYS_INLINE uintptr_t thread_tls_get(thread_t *t, uint entry)
300: #define thread_tls_set(t,e,v) \
308: static inline void thread_set_flag(thread_t *t, uint flag, bool enable)
319: static inline bool thread_get_flag(thread_t *t, uint flag)
338: static inline void thread_set_flag_exit_on_panic(thread_t *t, bool enable)
343: static inline bool thread_get_flag_exit_on_panic(thread_t *t)
350: struct thread_stats {
368: #define THREAD_STATS_INC(name) do { thread_stats[arch_curr_cpu_num()].name++; } while(0)
372: #define THREAD_STATS_INC(name) do { } while (0)
24: #define __KERNEL_THREAD_H
293: static inline __ALWAYS_INLINE uintptr_t __thread_tls_set(thread_t *t,
23: #ifndef __KERNEL_THREAD_H
32: #include <arch/thread.h>
62: /* thread local storage */
103:     enum thread_state state;
119:     struct arch_thread arch;
122:     thread_start_routine entry;
129:     /* thread local storage */
145: /* thread priority */
172: void thread_init_early(void);
173: void thread_init(void);
174: void thread_become_idle(void) __NO_RETURN;
175: void thread_secondary_cpu_init_early(void);
176: void thread_secondary_cpu_entry(void) __NO_RETURN;
177: void thread_set_name(const char *name);
180:  * thread_set_priority() - set priority of current thread
181:  * @priority:      Priority for the current thread,
186:  *                 holding the thread lock.
188: void thread_set_priority(int priority);
191:  * thread_set_pinned_cpu() - Pin thread to a given CPU.
192:  * @t:             Thread to pin
193:  * @cpu:           cpu id on which to pin the thread
196:  *                 holding the thread lock.
198: void thread_set_pinned_cpu(thread_t* t, int cpu);
200: thread_t *thread_create(const char *name, thread_start_routine entry, void *arg, int priority, size_t stack_size);
201: thread_t *thread_create_etc(thread_t *t, const char *name, thread_start_routine entry, void *arg, int priority, void *stack, size_t stack_size, size_t shadow_stack_s...(5 bytes skipped)...
202: status_t thread_resume(thread_t *);
203: void thread_exit(int retcode) __NO_RETURN;
204: void thread_sleep_ns(lk_time_ns_t delay_ns);
205: void thread_sleep_until_ns(lk_time_ns_t target_time_ns);
207:     thread_sleep_ns(delay_ms * 1000ULL * 1000);
209: status_t thread_detach(thread_t *t);
210: status_t thread_join(thread_t *t, int *retcode, lk_time_t timeout);
211: status_t thread_detach_and_resume(thread_t *t);
212: status_t thread_set_real_time(thread_t *t);
214: void dump_thread(thread_t *t);
215: void arch_dump_thread(thread_t *t);
219: void thread_yield(void); /* give up the cpu voluntarily */
220: void thread_preempt(void); /* get preempted (inserted into head of run queue) */
221: void thread_block(void); /* block on something and reschedule */
222: void thread_unblock(thread_t *t, bool resched); /* go back in the run queue */
225: enum handler_return thread_timer_tick(void);
227: /* the current thread */
228: thread_t *get_current_thread(void);
229: void set_current_thread(thread_t *);
232: extern spin_lock_t thread_lock;
233: extern atomic_uint thread_lock_owner;
236:     return atomic_load_explicit(&thread_lock_owner, memory_order_relaxed);
240:     DEBUG_ASSERT(thread_lock_owner_get() == SMP_MAX_CPUS);
241:     atomic_store_explicit(&thread_lock_owner, arch_curr_cpu_num(),
247:     DEBUG_ASSERT(thread_lock_owner_get() == arch_curr_cpu_num());
248:     atomic_store_explicit(&thread_lock_owner, SMP_MAX_CPUS,
254:     spin_lock_irqsave(&thread_lock, state); \
255:     thread_lock_complete()
258:     thread_unlock_prepare(); \
259:     spin_unlock_irqrestore(&thread_lock, state)
263:     spin_lock(&thread_lock);
264:     thread_lock_complete();
268:     thread_unlock_prepare();
269:     spin_unlock(&thread_lock);
277:     ret = thread_lock_owner_get() == arch_curr_cpu_num();
282: /* thread local storage */
290:     return thread_tls_get(get_current_thread(), entry);
303:         __thread_tls_set(t, e, v); \
306: #define tls_set(e,v) thread_tls_set(get_current_thread(), e, v)
310:     THREAD_LOCK(state);
316:     THREAD_UNLOCK(state);
322:     THREAD_LOCK(state);
324:     THREAD_UNLOCK(state);
329:  * thread_set_flag_exit_on_panic - Set flag to ignore panic in specific thread
330:  * @t:       Thread to set flag on
331:  * @enable:  If %true, exit thread instead of halting system if panic is called
340:     thread_set_flag(t, THREAD_FLAG_EXIT_ON_PANIC, enable);
345:     return thread_get_flag(t, THREAD_FLAG_EXIT_ON_PANIC);
348: /* thread level statistics */
349: #if THREAD_STATS
366: extern struct thread_stats thread_stats[SMP_MAX_CPUS];
216: void dump_all_threads(void);
335:  * Should only be used for kernel test threads as it is generally not safe to
github.com/apache/activemq-cpp:activemq-cpp/src/main/decaf/util/concurrent/ThreadPoolExecutor.cpp: [ master, ]
153:             Pointer<Thread> thread;
957:         bool prestartCoreThread() {
1353: ThreadPoolExecutor::ThreadPoolExecutor(int corePoolSize, int maxPoolSize,
1382: ThreadPoolExecutor::ThreadPoolExecutor(int corePoolSize, int maxPoolSize,
1414: ThreadPoolExecutor::ThreadPoolExecutor(int corePoolSize, int maxPoolSize,
1446: ThreadPoolExecutor::ThreadPoolExecutor(int corePoolSize, int maxPoolSize,
1690: bool ThreadPoolExecutor::prestartCoreThread() {
1478: ThreadPoolExecutor::~ThreadPoolExecutor() {
315:         bool coreThreadsCanTimeout;
961:         int prestartAllCoreThreads() {
969:         void allowCoreThreadTimeOut(bool value) {
1614: void ThreadPoolExecutor::setThreadFactory(ThreadFactory* factory) {
1627: ThreadFactory* ThreadPoolExecutor::getThreadFactory() const {
1670: void ThreadPoolExecutor::allowCoreThreadTimeout(bool value) {
1685: bool ThreadPoolExecutor::allowsCoreThreadTimeout() const {
1695: int ThreadPoolExecutor::prestartAllCoreThreads() {
61:      * task deletion logic can remain unchanged and thread safe.
102:      * for example when a ThreadFactory fails to create a thread when
114:      *             the thread transitioning to state TIDYING
168:                 AbstractQueuedSynchronizer(), Runnable(), thread(), firstTask(task), kernel(kernel), completedTasks(0) {
175:                 this->thread.reset(kernel->factory->newThread(this));
210:                     setExclusiveOwnerThread(Thread::currentThread());
226:          * to the Timer's thread.
307:          * up on a separate thread because the Worker generally adds itself to the deadWorkers
422:                     worker->thread->join();
593:                     iter->next()->thread->interrupt();
611:          *      currently waiting.  Interrupting any arbitrary thread ensures that
624:                     Pointer<Thread> thread = worker->thread;
625:                     if (!thread->isInterrupted() && worker->tryLock()) {
627:                             thread->interrupt();
656:          * Ensures that unless the pool is stopping, the current thread does not have
661:             if (this->runStateLessThan(ctl.get(), STOP) && Thread::interrupted() &&
664:                 Thread::currentThread()->interrupt();
690:          * usually leads processWorkerExit to replace this thread.
695:          * stopping, this thread does not have its interrupt set.
698:          * might throw an exception, in which case we cause thread to die
708:          * thread's UncaughtExceptionHandler).  Any thrown exception also
709:          * conservatively causes thread to die.
712:          * also throw an exception, which will also cause thread to
717:          * and the thread's UncaughtExceptionHandler have as accurate
732:                         this->parent->beforeExecute(w->thread.get(), task);
796:              * start a new thread with the given command as its first
802:              * to double-check whether we should have added a thread
806:              * stopped, or start a new thread if there are none.
809:              * thread.  If it fails, we know we are shut down or saturated
1106:          * if the thread factory fails to create a thread when asked, which requires
1111:          *      The task the new thread should run first (or null if none).
1153:             Pointer<Thread> t = w->thread;
1187:             // It is possible (but unlikely) for a thread to have been added to
1189:             // could result in a rare missed interrupt, because Thread::interrupt
1190:             // is not guaranteed to have any effect on a non-yet-started Thread
1191:             // (see Thread#interrupt).
1203:          * thread from worker set, and possibly terminates the pool or replaces the
1329:          * abrupt termination of a thread (see processWorkerExit). Other
1710: void ThreadPoolExecutor::beforeExecute(Thread* thread DECAF_UNUSED, Runnable* task DECAF_UNUSED) {
18: #include "ThreadPoolExecutor.h"
89:      *   workerCount, indicating the effective number of threads
93:      * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
101:      * transiently different from the actual number of live threads,
103:      * asked, and when exiting threads are still performing
133:      * Threads waiting in awaitTermination() will return when the
172:                         "ThreadPoolExecutor Worker requires non-NULL pointer to parent ExecutorKernel");
217:                 this->setExclusiveOwnerThread(NULL);
291:         ThreadPoolExecutor* parent;
294:          * List containing all worker threads in pool. Accessed only when holding mainLock.
318:          * The queue used for holding tasks and handing off to worker threads.
333:          * Otherwise exiting threads would concurrently interrupt those that have not
349:         Pointer<ThreadFactory> factory;
354:         ExecutorKernel(ThreadPoolExecutor* parent,
357:                        ThreadFactory* threadFactory, RejectedExecutionHandler* handler) :
381:            if(workQueue == NULL || threadFactory == NULL || handler == NULL) {
389:            this->factory.reset(threadFactory);
417:                 // Ensure dead Worker Threads are destroyed, the Timer might not have
586:          * Force an interrupt of all threads even if they are currently active.
603:          * Interrupts threads that might be waiting for tasks (as indicated by not
610:          *      interrupted to propagate shutdown signals in case all threads are
795:              * 1. If fewer than corePoolSize threads are running, try to
799:              * threads when it shouldn't, by returning false.
932:                 // We don't really know how many new threads are "needed".
972:                     "Core threads must have nonzero keep alive times");
990:                     "Core threads must have nonzero keep alive times");
1113:          *      to bypass queuing when there are fewer than corePoolSize threads
1115:          *      (in which case we must bypass queue). Initially idle threads are
1116:          *      usually created via prestartCoreThread or to replace other dying workers.
1157:                 // Recheck while holding lock. Back out on ThreadFactory failure or if
1201:          * worker threads. Unless completedAbruptly is set, assumes that workerCount
1365:         Pointer<RejectedExecutionHandler> handler(new ThreadPoolExecutor::AbortPolicy());
1366:         Pointer<ThreadFactory> threadFactory(Executors::getDefaultThreadFactory());
1370:             threadFactory.get(), handler.get());
1373:         threadFactory.release();
1399:         Pointer<ThreadFactory> threadFactory(Executors::getDefaultThreadFactory());
1403:             threadFactory.get(), handler);
1405:         threadFactory.release();
1417:                                        ThreadFactory* threadFactory) :
1427:         if(threadFactory == NULL) {
1428:             throw NullPointerException(__FILE__, __LINE__, "The ThreadFactory pointer cannot be NULL.");
1431:         Pointer<RejectedExecutionHandler> handler(new ThreadPoolExecutor::AbortPolicy());
1435:             threadFactory, handler.get());
1449:                                        ThreadFactory* threadFactory, RejectedExecutionHandler* handler) :
1463:         if(threadFactory == NULL) {
1464:             throw NullPointerException(__FILE__, __LINE__, "The ThreadFactory pointer cannot be NULL.");
1469:             threadFactory, handler);
1488: void ThreadPoolExecutor::execute(Runnable* task) {
1495:                 "ThreadPoolExecutor::execute - Supplied Runnable pointer was NULL.");
1507: void ThreadPoolExecutor::execute(Runnable* task, bool takeOwnership) {
1514:                 "ThreadPoolExecutor::execute - Supplied Runnable pointer was NULL.");
1526: void ThreadPoolExecutor::shutdown() {
1536: ArrayList<Runnable*> ThreadPoolExecutor::shutdownNow() {
1549: bool ThreadPoolExecutor::awaitTermination(long long timeout, const TimeUnit& unit) {
1559: int ThreadPoolExecutor::getPoolSize() const {
1564: int ThreadPoolExecutor::getCorePoolSize() const {
1569: void ThreadPoolExecutor::setCorePoolSize(int poolSize) {
1579: int ThreadPoolExecutor::getMaximumPoolSize() const {
1584: void ThreadPoolExecutor::setMaximumPoolSize(int maxSize) {
1594: long long ThreadPoolExecutor::getTaskCount() const {
1599: int ThreadPoolExecutor::getActiveCount() const {
1604: long long ThreadPoolExecutor::getCompletedTaskCount() const {
1609: int ThreadPoolExecutor::getLargestPoolSize() const {
1617:         throw NullPointerException(__FILE__, __LINE__, "Cannot assign a NULL ThreadFactory.");
1621:         Pointer<ThreadFactory> temp(factory);
1632: RejectedExecutionHandler* ThreadPoolExecutor::getRejectedExecutionHandler() const {
1637: void ThreadPoolExecutor::setRejectedExecutionHandler(RejectedExecutionHandler* handler) {
1650: BlockingQueue<Runnable*>* ThreadPoolExecutor::getQueue() {
1655: bool ThreadPoolExecutor::isShutdown() const {
1660: bool ThreadPoolExecutor::isTerminated() const {
1665: bool ThreadPoolExecutor::isTerminating() const {
1675: long long ThreadPoolExecutor::getKeepAliveTime(const TimeUnit& unit) const {
1680: void ThreadPoolExecutor::setKeepAliveTime(long long timeout, const TimeUnit& unit) {
1691:     return this->kernel->prestartCoreThread();
1700: bool ThreadPoolExecutor::remove(decaf::lang::Runnable* task) {
1705: void ThreadPoolExecutor::purge() {
1714: void ThreadPoolExecutor::afterExecute(Runnable* task DECAF_UNUSED, decaf::lang::Throwable* error DECAF_UNUSED) ...(1 bytes skipped)...
1718: void ThreadPoolExecutor::terminated() {
1722: void ThreadPoolExecutor::onShutdown() {
366:            coreThreadsCanTimeout(false),
540:          * allow access from ScheduledThreadPoolExecutor.
669:          * State check needed by ScheduledThreadPoolExecutor to enable running
975:             if (value != this->coreThreadsCanTimeout) {
976:                 this->coreThreadsCanTimeout = value;
988:             if (time == 0 && this->coreThreadsCanTimeout) {
1232:                     int min = this->coreThreadsCanTimeout ? 0 : corePoolSize;
1254:          *     {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
1277:                     timed = this->coreThreadsCanTimeout || wc > this->corePoolSize;
1671:     this->kernel->allowCoreThreadTimeOut(value);
1686:     return this->kernel->coreThreadsCanTimeout;
1696:     return this->kernel->prestartAllCoreThreads();
github.com/rosjava/rosjava_core:apache_xmlrpc_common/src/main/java/org/apache/xmlrpc/util/ThreadPool.java: [ kinetic, ]
50:         private Thread thread;
28: public class ThreadPool {
111: 	private final ThreadGroup threadGroup;
123: 	public ThreadPool(int pMaxSize, String pName) {
113: 	private final List waitingThreads = new ArrayList();
114: 	private final List runningThreads = new ArrayList();
226: 	public int getMaxThreads() { return maxSize; }
231:     public synchronized int getNumThreads() { return num; }
25: /** Simple thread pool. A task is executed by obtaining a thread from
29: 	/** The thread pool contains instances of {@link ThreadPool.Task}.
33: 		 * @throws Throwable The task failed, and the worker thread won't be used again.
52:             thread = new Thread(pGroup, pGroup.getName() + "-" + pNum){
80:             thread.start();
93:             synchronized (thread) {
94:                 thread.notify();
105:             synchronized (thread) {
106:                 thread.notify();
121: 	 * @param pName Thread group name.
51:         Poolable(ThreadGroup pGroup, int pNum) {
120: 	 * @param pMaxSize Maximum number of concurrent threads.
125: 		threadGroup = new ThreadGroup(pName);
167: 	 * might consider to use the {@link #addTask(ThreadPool.Task)} method instead.
189:             poolable = new Poolable(threadGroup, num++);
223: 	/** Returns the maximum number of concurrent threads.
224: 	 * @return Maximum number of threads.
228: 	/** Returns the number of threads, which have actually been created,
229:      * as opposed to the number of currently running threads.
129:         runningThreads.remove(pPoolable);
130:         waitingThreads.remove(pPoolable);
138: 	        if (runningThreads.remove(pPoolable)) {
139: 	            if (maxSize != 0  &&  runningThreads.size() + waitingThreads.size() >= maxSize) {
142: 	                waitingThreads.add(pPoolable);
179:         if (maxSize != 0  &&  runningThreads.size() >= maxSize) {
186:         if (waitingThreads.size() > 0) {
187:             poolable = (Poolable) waitingThreads.remove(waitingThreads.size()-1);
191:         runningThreads.add(poolable);
213:         while (!waitingThreads.isEmpty()) {
214:             Poolable poolable = (Poolable) waitingThreads.remove(waitingThreads.size()-1);
217:         while (!runningThreads.isEmpty()) {
218:             Poolable poolable = (Poolable) runningThreads.remove(runningThreads.size()-1);
github.com/GNOME/libdazzle:src/search/dzl-fuzzy-index-cursor.c: [ mainline, ]
65:   const gchar                     *needle;
408:   lookup.needle = query;
550:   g_task_run_in_thread (task, dzl_fuzzy_index_cursor_worker);
android.googlesource.com/platform/external/starlark-go:starlark/eval.go: [ master, ]
30: type Thread struct {
27: // A Thread contains the state of a Starlark thread,
28: // such as its call stack and thread-local storage.
29: // The Thread is threaded throughout the evaluator.
31: 	// Name is an optional name that describes the thread, for debugging.
40: 	Print func(thread *Thread, msg string)
48: 	Load func(thread *Thread, module string) (StringDict, error)
50: 	// steps counts abstract computation steps executed by this thread.
56: 	// locals holds arbitrary "thread-local" Go values belonging to the client.
65: // by this thread. It is incremented by the interpreter. It may be used
70: func (thread *Thread) ExecutionSteps() uint64 {
71: 	return thread.steps
75: // computation steps that may be executed by this thread. If the
76: // thread's step counter exceeds this limit, the interpreter calls
77: // thread.Cancel("too many steps").
78: func (thread *Thread) SetMaxExecutionSteps(max uint64) {
79: 	thread.maxSteps = max
82: // Cancel causes execution of Starlark code in the specified thread to
85: // if the thread is currently in a call to a built-in function.
89: // Unlike most methods of Thread, it is safe to call Cancel from any
90: // goroutine, even if the thread is actively executing.
91: func (thread *Thread) Cancel(reason string) {
93: 	atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&thread.cancelReason)), nil, unsafe.Pointer(&reason))
96: // SetLocal sets the thread-local value associated with the specified key.
98: func (thread *Thread) SetLocal(key string, value interface{}) {
99: 	if thread.locals == nil {
100: 		thread.locals = make(map[string]interface{})
102: 	thread.locals[key] = value
105: // Local returns the thread-local value associated with the specified key.
106: func (thread *Thread) Local(key string) interface{} {
107: 	return thread.locals[key]
115: func (thread *Thread) CallFrame(depth int) CallFrame {
116: 	return thread.frameAt(depth).asCallFrame()
119: func (thread *Thread) frameAt(depth int) *frame {
120: 	return thread.stack[len(thread.stack)-1-depth]
123: // CallStack returns a new slice containing the thread's stack of call frames.
124: func (thread *Thread) CallStack() CallStack {
125: 	frames := make([]CallFrame, len(thread.stack))
126: 	for i, fr := range thread.stack {
133: func (thread *Thread) CallStackDepth() int { return len(thread.stack) }
230: // a copy of the thread's stack at the moment of the error.
251: func (thread *Thread) evalError(err error) *EvalError {
254: 		CallStack: thread.CallStack(),
318: // Thread is the state associated with the Starlark thread.
332: func ExecFile(thread *Thread, filename string, src interface{}, predeclared StringDict) (StringDict, error) {
339: 	g, err := mod.Init(thread, predeclared)
408: func (prog *Program) Init(thread *Thread, predeclared StringDict) (StringDict, error) {
411: 	_, err := Call(thread, toplevel, nil, nil)
418: // ExecREPLChunk compiles and executes file f in the specified thread
426: func ExecREPLChunk(f *syntax.File, thread *Thread, globals StringDict) error {
457: 	_, err := Call(thread, toplevel, nil, nil)
512: func Eval(thread *Thread, filename string, src interface{}, env StringDict) (Value, error) {
521: 	return Call(thread, f, nil, nil)
536: func EvalExpr(thread *Thread, expr syntax.Expr, env StringDict) (Value, error) {
541: 	return Call(thread, fn, nil, nil)
1002: 			needle, ok := x.(String)
1006: 			return Bool(strings.Contains(string(y), string(needle))), nil
1008: 			switch needle := x.(type) {
1010: 				return Bool(strings.Contains(string(y), string(needle))), nil
1013: 				if err := AsInt(needle, &b); err != nil {
1188: func Call(thread *Thread, fn Value, args Tuple, kwargs []Tuple) (Value, error) {
1196: 	// Optimization: use slack portion of thread.stack
1198: 	if n := len(thread.stack); n < cap(thread.stack) {
1199: 		fr = thread.stack[n : n+1][0]
1205: 	if thread.stack == nil {
1206: 		// one-time initialization of thread
1207: 		if thread.maxSteps == 0 {
1208: 			thread.maxSteps-- // (MaxUint64)
1212: 	thread.stack = append(thread.stack, fr) // push
1216: 	thread.beginProfSpan()
1217: 	result, err := c.CallInternal(thread, args, kwargs)
1218: 	thread.endProfSpan()
1228: 			err = thread.evalError(err)
1233: 	thread.stack = thread.stack[:len(thread.stack)-1] // pop
android.googlesource.com/platform/external/rust/crates/crossbeam-utils:src/thread.rs: [ master, ]
484:     thread: thread::Thread,
541:     pub fn thread(&self) -> &thread::Thread {
316: pub struct ScopedThreadBuilder<'scope, 'env> {
321: impl<'scope, 'env> ScopedThreadBuilder<'scope, 'env> {
6: //! use crossbeam_utils::thread;
14: //! thread::scope(|s| {
28: //! use std::thread;
39: //!     threads.push(thread::spawn(move || {
44: //! for thread in threads {
45: //!     thread.join().unwrap();
72: //! If a variable is borrowed by a thread, the thread must complete before the variable is
73: //! destroyed. Threads spawned using [`std::thread::spawn`] can only borrow variables with the
74: //! `'static` lifetime because the borrow checker cannot be sure when the thread will complete.
77: //! scope. Whenever a scope spawns a thread, it promises to join the thread before the scope ends.
84: //! tricky because argument `s` lives *inside* the invocation of `thread::scope()` and as such
88: //! use crossbeam_utils::thread;
90: //! thread::scope(|s| {
94: //!         s.spawn(|_| println!("nested thread"));
99: //! Fortunately, there is a solution. Every scoped thread is passed a reference to its scope as an
103: //! use crossbeam_utils::thread;
105: //! thread::scope(|s| {
109: //!         s.spawn(|_| println!("nested thread"));
120: use std::thread;
138: /// use crossbeam_utils::thread;
142: /// thread::scope(|s| {
144: ///         println!("A child thread borrowing `var`: {:?}", var);
148: pub fn scope<'env, F, R>(f: F) -> thread::Result<R>
194:     /// The list of the thread join handles.
195:     handles: SharedVec<SharedOption<thread::JoinHandle<()>>>,
207:     /// Spawns a scoped thread.
210:     /// is that this thread is scoped, meaning it's guaranteed to terminate before the scope exits,
213:     /// The scoped thread is passed a reference to this scope as an argument, which can be used for
217:     /// [join](ScopedJoinHandle::join) the thread before the scope exits.
219:     /// This will create a thread using default parameters of [`ScopedThreadBuilder`], if you want to specify the
220:     /// stack size or the name of the thread, use this API instead.
222:     /// [`spawn`]: std::thread::spawn
226:     /// Panics if the OS fails to create a thread; use [`ScopedThreadBuilder::spawn`]
232:     /// use crossbeam_utils::thread;
234:     /// thread::scope(|s| {
236:     ///         println!("A child thread is running");
240:     ///     // Join the thread and retrieve its result.
253:             .expect("failed to spawn scoped thread")
256:     /// Creates a builder that can configure a thread before spawning.
261:     /// use crossbeam_utils::thread;
263:     /// thread::scope(|s| {
265:     ///         .spawn(|_| println!("A child thread is running"))
272:             builder: thread::Builder::new(),
283: /// Configures the properties of a new thread.
287: /// - [`name`]: Specifies an [associated name for the thread][naming-threads].
288: /// - [`stack_size`]: Specifies the [desired stack size for the thread][stack-size].
291: /// thread handle with the given configuration.
295: /// thread.
300: /// use crossbeam_utils::thread;
302: /// thread::scope(|s| {
304: ///         .spawn(|_| println!("Running a child thread"))
313: /// [naming-threads]: std::thread#naming-threads
314: /// [stack-size]: std::thread#stack-size
318:     builder: thread::Builder,
322:     /// Sets the name for the new thread.
331:     /// use crossbeam_utils::thread;
332:     /// use std::thread::current;
334:     /// thread::scope(|s| {
336:     ///         .name("my thread".to_string())
337:     ///         .spawn(|_| assert_eq!(current().name(), Some("my thread")))
342:     /// [naming-threads]: std::thread#naming-threads
348:     /// Sets the size of the stack for the new thread.
357:     /// use crossbeam_utils::thread;
359:     /// thread::scope(|s| {
362:     ///         .spawn(|_| println!("Running a child thread"))
367:     /// [stack-size]: std::thread#stack-size
373:     /// Spawns a scoped thread with this configuration.
375:     /// The scoped thread is passed a reference to this scope as an argument, which can be used for
378:     /// The returned handle can be used to manually join the thread before the scope exits.
383:     /// [`io::Result`] to capture any failure to create the thread at
390:     /// Panics if a thread name was set and it contained null bytes.
395:     /// use crossbeam_utils::thread;
397:     /// thread::scope(|s| {
400:     ///             println!("A child thread is running");
405:     ///     // Join the thread and retrieve its result.
419:         // Spawn the thread and grab its join handle and thread handle.
420:         let (handle, thread) = {
423:             // A clone of the scope that will be moved into the new thread.
430:             // Spawn the thread.
452:             let thread = handle.thread().clone();
454:             (handle, thread)
463:             thread,
472: /// A handle that can be used to join its scoped thread.
477:     /// A join handle to the spawned thread.
478:     handle: SharedOption<thread::JoinHandle<()>>,
483:     /// A handle to the the spawned thread.
491:     /// Waits for the thread to finish and returns its result.
493:     /// If the child thread panics, an error is returned.
497:     /// This function may panic on some platforms if a thread attempts to join itself or otherwise
503:     /// use crossbeam_utils::thread;
505:     /// thread::scope(|s| {
506:     ///     let handle1 = s.spawn(|_| println!("I'm a happy thread :)"));
507:     ///     let handle2 = s.spawn(|_| panic!("I'm a sad thread :("));
509:     ///     // Join the first thread and verify that it succeeded.
513:     ///     // Join the second thread and verify that it panicked.
518:     pub fn join(self) -> thread::Result<T> {
523:         // Join the thread and then take the result out of its inner closure.
529:     /// Returns a handle to the underlying thread.
534:     /// use crossbeam_utils::thread;
536:     /// thread::scope(|s| {
537:     ///     let handle = s.spawn(|_| println!("A child thread is running"));
538:     ///     println!("The child thread ID: {:?}", handle.thread().id());
542:         &self.thread
548:         use std::os::unix::thread::{JoinHandleExt, RawPthread};
1: //! Threads that can borrow variables from the stack.
3: //! Create a scope when spawned threads need to access variables on the stack:
23: //! # Why scoped threads?
25: //! Suppose we wanted to re-write the previous example using plain threads:
36: //! let mut threads = Vec::new();
64: //! The problem here is that spawned threads are not allowed to borrow variables on stack because
67: //! Scoped threads are a mechanism to guarantee to the compiler that spawned threads will be joined
70: //! # How scoped threads work
76: //! A scope creates a clear boundary between variables outside the scope and threads inside the
78: //! This way we guarantee to the borrow checker that scoped threads only live within the scope and
81: //! # Nesting scoped threads
83: //! Sometimes scoped threads need to spawn more threads within the same scope. This is a little
85: //! cannot be borrowed by scoped threads:
100: //! argument, which can be used for spawning nested threads:
128: /// Creates a new scope for spawning threads.
130: /// All child threads that haven't been manually joined will be automatically joined just before
131: /// this function invocation ends. If all joined threads have successfully completed, `Ok` is
132: /// returned with the return value of `f`. If any of the joined threads has panicked, an `Err` is
133: /// returned containing errors from panicked threads.
166:     // Join all remaining spawned threads.
178:     // If any of the child threads have panicked, return the panic errors.
192: /// A scope for spawning threads.
214:     /// spawning nested threads.
326:     /// For more information about named threads, see [here][naming-threads].
352:     /// For more information about the stack size for threads, see [here][stack-size].
376:     /// spawning nested threads.
498:     /// may create a deadlock with joining threads.
520:         // for nested scopes before joining remaining threads.
551:             fn as_pthread_t(&self) -> RawPthread {
553:                 // for nested scopes before joining remaining threads.
555:                 handle.as_ref().unwrap().as_pthread_t()
557:             fn into_pthread_t(self) -> RawPthread {
558:                 self.as_pthread_t()
567:                 // for nested scopes before joining remaining threads.
269:     pub fn builder<'scope>(&'scope self) -> ScopedThreadBuilder<'scope, 'env> {
270:         ScopedThreadBuilder {
309: /// [`name`]: ScopedThreadBuilder::name
310: /// [`stack_size`]: ScopedThreadBuilder::stack_size
311: /// [`spawn`]: ScopedThreadBuilder::spawn
343:     pub fn name(mut self, name: String) -> ScopedThreadBuilder<'scope, 'env> {
368:     pub fn stack_size(mut self, size: usize) -> ScopedThreadBuilder<'scope, 'env> {
475: /// [`ScopedThreadBuilder::spawn`] method.
github.com/google/starlark-go:starlark/eval.go: [ master, ] Duplicate result
github.com/google/skylark:eval.go: [ master, ]
29: type Thread struct {
26: // A Thread contains the state of a Skylark thread,
27: // such as its call stack and thread-local storage.
28: // The Thread is threaded throughout the evaluator.
36: 	Print func(thread *Thread, msg string)
44: 	Load func(thread *Thread, module string) (StringDict, error)
46: 	// locals holds arbitrary "thread-local" Go values belonging to the client.
51: // SetLocal sets the thread-local value associated with the specified key.
53: func (thread *Thread) SetLocal(key string, value interface{}) {
54: 	if thread.locals == nil {
55: 		thread.locals = make(map[string]interface{})
57: 	thread.locals[key] = value
60: // Local returns the thread-local value associated with the specified key.
61: func (thread *Thread) Local(key string) interface{} {
62: 	return thread.locals[key]
67: func (thread *Thread) Caller() *Frame { return thread.frame.parent }
70: func (thread *Thread) TopFrame() *Frame { return thread.frame }
117: // The Frames of a thread are structured as a spaghetti stack, not a
217: // Thread is the state associated with the Skylark thread.
231: func ExecFile(thread *Thread, filename string, src interface{}, predeclared StringDict) (StringDict, error) {
238: 	g, err := mod.Init(thread, predeclared)
280: func (prog *Program) Init(thread *Thread, predeclared StringDict) (StringDict, error) {
283: 	_, err := Call(thread, toplevel, nil, nil)
328: func Eval(thread *Thread, filename string, src interface{}, env StringDict) (Value, error) {
341: 	return Call(thread, fn, nil, nil)
724: 			needle, ok := x.(String)
728: 			return Bool(strings.Contains(string(y), string(needle))), nil
850: func Call(thread *Thread, fn Value, args Tuple, kwargs []Tuple) (Value, error) {
856: 	thread.frame = &Frame{parent: thread.frame, callable: c}
857: 	result, err := c.CallInternal(thread, args, kwargs)
858: 	thread.frame = thread.frame.parent
github.com/GNOME/pitivi:pitivi/utils/threads.py: [ mainline, ]
29: class Thread(threading.Thread, GObject.Object, Loggable):
72:     def add_thread(self, threadclass, *args):
65: class ThreadMaster(Loggable):
83:     def _thread_done_cb(self, thread):
87:     def wait_all_threads(self):
30:     """Event-powered thread."""
38:         threading.Thread.__init__(self)
42:         """Stops the thread, do not override."""
47:         """Runs the thread."""
52:         """Processes the thread.
59:         """Aborts the thread.
73:         """Instantiates the specified Thread class and starts it."""
74:         assert issubclass(threadclass, Thread)
75:         self.log("Adding thread of type %r", threadclass)
76:         thread = threadclass(*args)
77:         thread.connect("done", self._thread_done_cb)
78:         self.threads.append(thread)
80:         thread.start()
84:         self.log("thread %r is done", thread)
85:         self.threads.remove(thread)
92:             for thread in self.threads:
93:                 self.log("Waiting for thread to stop: %r", thread)
95:                     thread.join()
98:                     # Tried to join the current thread, or one
17: import threading
66:     """Threads controller."""
70:         self.threads = []
88:         """Waits until all running Threads controlled by this master stop."""
89:         self.log("Waiting for threads to stop")
91:         while joinedthreads < len(self.threads):
90:         joinedthreads = 0
96:                     joinedthreads += 1
android.googlesource.com/platform/system/nfc:src/adaptation/NfcAdaptation.cc: [ master, ]
473: uint32_t NfcAdaptation::Thread(__attribute__((unused)) uint32_t arg) {
835: ThreadMutex::ThreadMutex() {
885: ThreadCondVar::ThreadCondVar() {
852: ThreadMutex::~ThreadMutex() { pthread_mutex_destroy(&mMutex); }
903: ThreadCondVar::~ThreadCondVar() { pthread_cond_destroy(&mCondVar); }
942: AutoThreadMutex::AutoThreadMutex(ThreadMutex& m) : mm(m) { mm.lock(); }
953: AutoThreadMutex::~AutoThreadMutex() { mm.unlock(); }
293:   // Android already logs thread_id, proc_id, timestamp, so disable those.
374:     GKI_create_task((TASKPTR)Thread, MMI_TASK, (int8_t*)"NFCA_THREAD", nullptr, 0,
440: ** Description: signal the CondVar to release the thread that is waiting
466: ** Function:    NfcAdaptation::Thread()
474:   const char* func = "NfcAdaptation::Thread";
61: ThreadMutex NfcAdaptation::sLock;
64: ThreadCondVar NfcAdaptation::mHalOpenCompletedEvent;
65: ThreadCondVar NfcAdaptation::mHalCloseCompletedEvent;
309:     // of a byte array is ambiguous and needlessly difficult to configure.
371:                   (pthread_cond_t*)nullptr, nullptr);
375:                     (pthread_cond_t*)nullptr, nullptr);
468: ** Description: Creates work threads
478:     ThreadCondVar CondVar;
481:                     (pthread_cond_t*)CondVar, (pthread_mutex_t*)CondVar);
828: ** Function:    ThreadMutex::ThreadMutex()
836:   pthread_mutexattr_t mutexAttr;
838:   pthread_mutexattr_init(&mutexAttr);
839:   pthread_mutex_init(&mMutex, &mutexAttr);
840:   pthread_mutexattr_destroy(&mutexAttr);
845: ** Function:    ThreadMutex::~ThreadMutex()
856: ** Function:    ThreadMutex::lock()
863: void ThreadMutex::lock() { pthread_mutex_lock(&mMutex); }
867: ** Function:    ThreadMutex::unblock()
874: void ThreadMutex::unlock() { pthread_mutex_unlock(&mMutex); }
878: ** Function:    ThreadCondVar::ThreadCondVar()
886:   pthread_condattr_t CondAttr;
888:   pthread_condattr_init(&CondAttr);
889:   pthread_cond_init(&mCondVar, &CondAttr);
891:   pthread_condattr_destroy(&CondAttr);
896: ** Function:    ThreadCondVar::~ThreadCondVar()
907: ** Function:    ThreadCondVar::wait()
914: void ThreadCondVar::wait() {
915:   pthread_cond_wait(&mCondVar, *this);
916:   pthread_mutex_unlock(*this);
921: ** Function:    ThreadCondVar::signal()
928: void ThreadCondVar::signal() {
930:   pthread_cond_signal(&mCondVar);
199:   AutoThreadMutex a(sLock);
373:     AutoThreadMutex guard(mCondVar);
394:   AutoThreadMutex a(sLock);
479:     AutoThreadMutex guard(CondVar);
929:   AutoThreadMutex a(*this);
935: ** Function:    AutoThreadMutex::AutoThreadMutex()
946: ** Function:    AutoThreadMutex::~AutoThreadMutex()
android.googlesource.com/platform/external/rust/crates/syn:src/lib.rs: [ master, ]
808: mod thread;
139: //!     bad: std::thread::Thread,
149: //! error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied
152: //! 7 |     bad: std::thread::Thread,
153: //!   |     ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread`
266:     clippy::needless_doctest_main,
267:     clippy::needless_pass_by_value,
go.googlesource.com/debug:internal/core/thread.go: [ master, ]
8: type Thread struct {
7: // A Thread represents an operating system thread.
9: 	pid  uint64   // thread/process ID
15: func (t *Thread) Pid() uint64 {
19: // Regs returns the set of register values for the thread.
23: func (t *Thread) Regs() []uint64 {
27: func (t *Thread) PC() Address {
31: func (t *Thread) SP() Address {
github.com/vanadium/core:x/ref/runtime/internal/testing/concurrency/thread.go: [ master, ]
40: type thread struct {
54: func newThread(tid TID, clock clock) *thread {
11: // TID is the thread identifier type.
14: // Increasing is used to sort thread identifiers in an increasing order.
29: // TIDGenerator is used for generating unique thread identifiers.
38: // thread records the abstract state of a thread during an execution
41: 	// tid is the thread identifier.
44: 	// this thread.
47: 	// thread.
49: 	// req holds the current scheduling request of the thread.
53: // newThread is the thread factory.
55: 	return &thread{
61: // enabled checks if the thread can be scheduled given the current
63: func (t *thread) enabled(ctx *context) bool {
65: 		panic(fmt.Sprintf("Thread %v has no request.", t.tid))
70: // kind returns the kind of the thread transition.
71: func (t *thread) kind() transitionKind {
73: 		panic(fmt.Sprintf("Thread %v has no request.", t.tid))
78: // readSet returns the set of abstract resources read by the thread.
79: func (t *thread) readSet() resourceSet {
81: 		panic(fmt.Sprintf("Thread %v has no request.", t.tid))
87: // thread.
88: func (t *thread) writeSet() resourceSet {
90: 		panic(fmt.Sprintf("Thread %v has no request.", t.tid))
github.com/apache/xerces2-j:tests/thread/Test.java: [ trunk, ]
18: package thread;
657: class thread extends Thread {
661:     thread (ThreadInfo param) {
104: class ThreadInfo
111:     ThreadInfo() {
140: class ThreadParser extends HandlerBase
171: ThreadParser()
84:     int         numThreads;
109:     int        fThreadNum;      // Identifying number for this thread.
126: ThreadInfo      gThreadInfo[];
66:     int     checkSum;        // The XML checksum.  Set up by the main thread for
98: //  struct threadInfo  Holds information specific to an individual thread.
99: //                     One of these is set up for each thread in the test.
106:     boolean    fHeartBeat;      // Set true by the thread each time it finishes
577:         System.err.print("usage: java thread.Test [-v] [-threads nnn] [-time nnn] [-quiet] [-verbose] xmlfile...\n" +
600: //                          thread, before all of the worker threads are started.
649: //               thread termination.  Threads are stuck running here
651: //               main thread of the process (which never calls this
670:         System.out.println("Thread " + thInfo.fThreadNum + ": starting");
692:             System.out.println("Thread " + thInfo.fThreadNum +
726: } // class thread
796:         thread t = new thread(gThreadInfo[threadNum]);
803:     //                 display "." if some thread hasn't since previous "+"
811:             Thread.sleep(1000);
839:     //  To Do:  Run the main thread at higher priority, so that the worker threads
40:  * This program is a straight port of xerces/c/tests/ThreadTest.cpp
56: //                      and can safely be referenced by the test threads without
67:                              //   each file before the worker threads are started.
75: //                     During the test, the threads will access this info without
100: //                     The main program monitors the threads by looking
132: //  class ThreadParser   Bundles together a SAX parser and the SAX handlers
137: //                       in different threads.
168: //  ThreadParser constructor.  Invoked by the threads of the test program
263: //  addToCheckSum - private function, used within ThreadParser in
275: //  addToCheckSum - private function, used within ThreadParser in
468: } // class ThreadParser
516:             else if (argv[argnum].equals("-threads"))
583:             "     -threads nnn   Number of threads.  Default is 2. \n" +
644: //  threadMain   The main function for each of the swarm of test threads.
659:     ThreadInfo thInfo;
667:     ThreadParser thParser = null;
682:             thParser = new ThreadParser();
701:             System.err.println("\nThread " + thInfo.fThreadNum +
747:     // While we are still single threaded, parse each of the documents
751:     ThreadParser mainParser = new ThreadParser();
783:     //  Fire off the requested number of parallel threads
789:     gThreadInfo = new ThreadInfo[gRunInfo.numThreads];
791:     int threadNum;
792:     for (threadNum=0; threadNum < gRunInfo.numThreads; threadNum++)
794:         gThreadInfo[threadNum] = new ThreadInfo();
795:         gThreadInfo[threadNum].fThreadNum = threadNum;
801:     //  Loop, watching the heartbeat of the worker threads.
802:     //    Each second, display "+" when all threads have completed a parse
819:             for (threadNum=0; threadNum < gRunInfo.numThreads; threadNum++)
821:                 if (gThreadInfo[threadNum].fHeartBeat == false)
830:                 for (threadNum=0; threadNum < gRunInfo.numThreads; threadNum++)
831:                     gThreadInfo[threadNum].fHeartBeat = false;
838:     //  Tally up the total number of parses completed by each of the threads.
843:     for (threadNum=0; threadNum < gRunInfo.numThreads; threadNum++)
845:         totalParsesCompleted += gThreadInfo[threadNum].fParses;
853:     //  The threads are still running; we just return
114:         fThreadNum = -1;
487:     gRunInfo.numThreads = 2;
522:                     gRunInfo.numThreads = Integer.parseInt(argv[argnum]);
527:                 if (gRunInfo.numThreads < 0)
786:     if (gRunInfo.numThreads == 0)
github.com/apache/kafka:clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java: [ trunk, ]
357:     private final Thread thread;
1314:         private boolean threadShouldExit(long now, long curHardShutdownTimeMs) {
309:     static final String NETWORK_THREAD_PREFIX = "kafka-admin-client-thread";
284:  * This class is thread-safe.
307:      * Thread name prefix for admin client network thread
350:      * The runnable used in the service thread for this admin client.
355:      * The network service thread for this admin client.
361:      * and force the RPC thread to exit. If the admin client is not closing, this will be 0.
366:      * A factory which creates TimeoutProcessors for the RPC thread.
582:         String threadName = NETWORK_THREAD_PREFIX + " | " + clientId;
583:         this.thread = new KafkaThread(threadName, runnable, true);
591:         thread.start();
635:                 client.wakeup(); // Wake the thread, if it is blocked inside poll().
647:             log.debug("Waiting for the I/O thread to exit. Hard shutdown in {} ms.", deltaMs);
650:             // close() can be called by AdminClient thread when it invokes callback. That will
652:             if (Thread.currentThread() != thread) {
653:                 // Wait for the thread to be joined.
654:                 thread.join(waitTimeMs);
658:             log.debug("Interrupted while joining I/O thread", e);
659:             Thread.currentThread().interrupt();
968:          * Only accessed from this thread.
974:          * Only accessed from this thread.
980:          * Only accessed from this thread.
986:          * Only accessed from this thread.
1316:                 log.trace("All work has been completed, and the I/O thread is now exiting.");
1320:                 log.info("Forcing a hard I/O thread shutdown. Requests in progress will be aborted.");
1329:             log.debug("Thread starting");
1339:                     numTimedOut += timeoutProcessor.handleTimeouts(newCalls, "The AdminClient thread has exited.");
1341:                 numTimedOut += timeoutProcessor.handleTimeouts(pendingCalls, "The AdminClient thread has exited.");
1344:                         "The AdminClient thread has exited.");
1350:                 log.debug("Exiting AdminClientRunnable thread.");
1360:                 // Check if the AdminClient thread should shut down.
1415:          * If the AdminClient thread has exited, this will fail. Otherwise, it will succeed (even
1441:                 client.wakeup(); // wake the thread if it is in poll()
1443:                 log.debug("The AdminClient thread has exited. Timing out {}.", call);
1445:                     new TimeoutException("The AdminClient thread has exited."));
1461:                     new TimeoutException("The AdminClient thread is not accepting new calls."));
235: import org.apache.kafka.common.utils.KafkaThread;
1362:                 if ((curHardShutdownTimeMs != INVALID_SHUTDOWN_TIME) && threadShouldExit(now, curHardShutdownTimeMs))
github.com/kubernetes/minikube:site/package-lock.json: [ master, ]
1127:             "needle": "^2.2.1",
1108:         "needle": {
github.com/kubernetes/minikube:site/themes/docsy/userguide/package-lock.json: [ master, ]
1098:             "needle": "^2.2.1",
1079:         "needle": {
github.com/google/leveldb:benchmarks/db_bench.cc: [ master, ]
615:     ThreadState* thread;
358: struct ThreadState {
364:   ThreadState(int index, int seed) : tid(index), rand(seed), shared(nullptr) {}
612:   struct ThreadArg {
619:   static void ThreadBody(void* v) {
381:   int total_thread_count_;
72: static int FLAGS_threads = 1;
263:     // Just keep the messages from one thread
316:       // Rate is computed on actual elapsed time, not the sum of per-thread
343:   // Each thread goes through the following states:
357: // Per-thread state for concurrent executions of the same benchmark.
474:         total_thread_count_(0) {
569:         num_threads++;  // Add extra thread for writing
622:     ThreadState* thread = arg->thread;
634:     thread->stats.Start();
635:     (arg->bm->*(arg->method))(thread);
636:     thread->stats.Stop();
656:       ++total_thread_count_;
657:       // Seed the thread's random state deterministically based upon thread
660:       arg[i].thread = new ThreadState(i, /*seed=*/1000 + total_thread_count_);
661:       arg[i].thread->shared = &shared;
678:       arg[0].thread->stats.Merge(arg[i].thread->stats);
680:     arg[0].thread->stats.Report(name);
688:       delete arg[i].thread;
693:   void Crc32c(ThreadState* thread) {
702:       thread->stats.FinishedSingleOp();
708:     thread->stats.AddBytes(bytes);
709:     thread->stats.AddMessage(label);
712:   void SnappyCompress(ThreadState* thread) {
723:       thread->stats.FinishedSingleOp();
727:       thread->stats.AddMessage("(snappy failure)");
732:       thread->stats.AddMessage(buf);
733:       thread->stats.AddBytes(bytes);
737:   void SnappyUncompress(ThreadState* thread) {
748:       thread->stats.FinishedSingleOp();
753:       thread->stats.AddMessage("(snappy failure)");
755:       thread->stats.AddBytes(bytes);
781:   void OpenBench(ThreadState* thread) {
785:       thread->stats.FinishedSingleOp();
789:   void WriteSeq(ThreadState* thread) { DoWrite(thread, true); }
791:   void WriteRandom(ThreadState* thread) { DoWrite(thread, false); }
793:   void DoWrite(ThreadState* thread, bool seq) {
797:       thread->stats.AddMessage(msg);
808:         const int k = seq ? i + j : thread->rand.Uniform(FLAGS_num);
812:         thread->stats.FinishedSingleOp();
820:     thread->stats.AddBytes(bytes);
823:   void ReadSequential(ThreadState* thread) {
829:       thread->stats.FinishedSingleOp();
833:     thread->stats.AddBytes(bytes);
836:   void ReadReverse(ThreadState* thread) {
842:       thread->stats.FinishedSingleOp();
846:     thread->stats.AddBytes(bytes);
849:   void ReadRandom(ThreadState* thread) {
855:       const int k = thread->rand.Uniform(FLAGS_num);
860:       thread->stats.FinishedSingleOp();
864:     thread->stats.AddMessage(msg);
867:   void ReadMissing(ThreadState* thread) {
872:       const int k = thread->rand.Uniform(FLAGS_num);
876:       thread->stats.FinishedSingleOp();
880:   void ReadHot(ThreadState* thread) {
886:       const int k = thread->rand.Uniform(range);
889:       thread->stats.FinishedSingleOp();
893:   void SeekRandom(ThreadState* thread) {
899:       const int k = thread->rand.Uniform(FLAGS_num);
904:       thread->stats.FinishedSingleOp();
908:     thread->stats.AddMessage(msg);
911:   void SeekOrdered(ThreadState* thread) {
918:       k = (k + (thread->rand.Uniform(100))) % FLAGS_num;
922:       thread->stats.FinishedSingleOp();
927:     thread->stats.AddMessage(msg);
930:   void DoDelete(ThreadState* thread, bool seq) {
938:         const int k = seq ? i + j : (thread->rand.Uniform(FLAGS_num));
941:         thread->stats.FinishedSingleOp();
951:   void DeleteSeq(ThreadState* thread) { DoDelete(thread, true); }
953:   void DeleteRandom(ThreadState* thread) { DoDelete(thread, false); }
955:   void ReadWhileWriting(ThreadState* thread) {
956:     if (thread->tid > 0) {
957:       ReadRandom(thread);
959:       // Special thread that keeps writing until other threads are done.
964:           MutexLock l(&thread->shared->mu);
965:           if (thread->shared->num_done + 1 >= thread->shared->num_initialized) {
971:         const int k = thread->rand.Uniform(FLAGS_num);
982:       thread->stats.Start();
986:   void Compact(ThreadState* thread) { db_->CompactRange(nullptr, nullptr); }
71: // Number of concurrent threads to run.
359:   int tid;      // 0..n-1 when running in n threads
360:   Random rand;  // Has different seeds for different threads
516:       void (Benchmark::*method)(ThreadState*) = nullptr;
518:       int num_threads = FLAGS_threads;
606:         RunBenchmark(num_threads, name, method);
616:     void (Benchmark::*method)(ThreadState*);
620:     ThreadArg* arg = reinterpret_cast<ThreadArg*>(v);
648:                     void (Benchmark::*method)(ThreadState*)) {
651:     ThreadArg* arg = new ThreadArg[n];
662:       g_env->StartThread(ThreadBody, &arg[i]);
966:             // Other threads have finished
1052:     } else if (sscanf(argv[i], "--threads=%d%c", &n, &junk) == 1) {
1053:       FLAGS_threads = n;
github.com/osxfuse/osxfuse:prefpane/externals/google-toolbox-for-mac/XcodePlugin/XcodeHeaders/DevToolsInterface.h: [ master, ]
4872: - (id)thread;
4528:     PBXLSThread *_selectedThread;
4540: - (id)selectedThread;
4689: - (id)threadViewModule;
4771: - (id)selectedThread;
4875: - (BOOL)threadIsRunning;
4876: - (BOOL)threadIsRunningButNotStepping;
4877: - (BOOL)threadStepDidTimeout;
4878: - (BOOL)threadIsSteppable;
4899: - (void)continueThread;
7806: + (void)_startCrashCatchingServiceThread;
11480: - (void)threadRequestUpdateStack:(id)fp8;
11481: - (void)threadRequestStepInstruction:(id)fp8;
11482: - (void)threadRequestNextInstruction:(id)fp8;
11483: - (void)threadRequestStepInto:(id)fp8;
11484: - (void)threadRequestStepOver:(id)fp8;
11485: - (void)threadRequestStepOut:(id)fp8;
11487: - (void)threadRequestContinue:(id)fp8;
11862:     PBXLSThread *_currentThread;
11876: - (id)currentThread;
11883: - (id)threadGroups;
11884: - (id)threadGroupWithName:(id)fp8;
11887: - (id)threads;
11888: - (id)threadWithHandle:(unsigned long)fp8;
11909: - (id)parentThread;
11923: - (void)threadDidUpdate;
11939: @interface PBXLSThread : PBXLSModel
11967: - (int)threadState;
11968: - (int)threadStateStatus;
11997: - (id)threads;
14973:     NSThread *_taskThread;
4527:     NSPopUpButtonCell *_threadsPopUp;
4539: - (void)selectThread:(id)fp8;
4544: - (void)setSelectedThread:(id)fp8;
4554:     PBXDebugThreadViewModule *_threadViewModule;
4770: - (void)setSelectedThread:(id)fp8;
4858:     PBXDebugStackTableHeaderCell *_threadsTablePopUp;
11885: - (id)_threadsOfType:(int)fp8;
11941:     int _threadState;
11943:     int _threadStateStatus;
558: - (BOOL)usesThreadedAnimation;
559: - (void)setUsesThreadedAnimation:(BOOL)fp8;
3033: - (void)_finishSpeculativeCompilationInSeparateThreadWithSpecCompInfo:(id)fp8;
4535: - (id)selectedThreadViewModule;
4537: - (BOOL)allThreadsStopped;
4541: - (void)_emptyThreadsPopUp;
4546: - (void)setThreadsPopUp:(id)fp8;
4552:     PBXDebugProcessAndThreadModule *_processAndThreadModule;
4851: @interface PBXDebugThreadViewModule : PBXDebugDSModelViewModule
4867: - (id)stackTableThreadsPopUp;
7563: @interface PBXDebugProcessAndThreadModule : PBXDebugViewModule
11457: - (void)destroyThreadWithThreadHandle:(unsigned long)fp8;
11461: - (void)willUpdateThreads;
11462: - (void)didUpdateThreads;
11505: - (oneway void)requestSuspendAllThreads;
11872: - (void)debuggerWillUpdateThreads:(id)fp8;
11881: - (void)debuggerDidUpdateThreads:(id)fp8;
11886: - (id)nonRunningThreads;
11958: - (id)parentThreadGroup;
11983: @interface PBXLSThreadGroup : PBXLSModel
13118: - (BOOL)usesThreadedAnimation;
13119: - (void)setUsesThreadedAnimation:(BOOL)fp8;
13379: + (BOOL)useThreadedAnimation;
20671: - (BOOL)usesThreadedAnimation;
20672: - (void)setUsesThreadedAnimation:(BOOL)fp8;
11458: - (id)threadGroupWithName:(id)fp8 create:(BOOL)fp12;
11459: - (oneway void)setState:(int)fp8 status:(int)fp12 isCurrentThread:(BOOL)fp16 forServerThreadHandle:(unsigned long)fp20;
11486: - (void)threadRequest:(byref id)fp8 stepUntilLineNumber:(unsigned int)fp12;
11494: - (void)requestDebuggerMovePCInThread:(unsigned long)fp8 fileSpec:(id)fp12;
11640: - (void)requestPrintDescriptionInThread:(id)fp8 atStackFrame:(id)fp12;
11875: - (void)debugger:(id)fp8 setCurrentThread:(id)fp12;
11995: - (void)debugger:(id)fp8 addThread:(id)fp12;
11996: - (void)debugger:(id)fp8 removeThread:(id)fp12;
11455: - (void)createThreadWithThreadHandle:(unsigned long)fp8 name:(id)fp12 inThreadGroupNamed:(id)fp16;
11873: - (void)debugger:(id)fp8 addThreadGroup:(id)fp12;
11874: - (void)debugger:(id)fp8 removeThreadGroup:(id)fp12;
11970: - (void)debugger:(id)fp8 setThreadState:(int)fp12 status:(int)fp16;
14988: - (BOOL)detachNewThreadSelector:(SEL)fp8 cancelSelector:(SEL)fp12 toTarget:(id)fp16 withObject:(id)fp20;
github.com/google/j2objc:jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/CompletableFuture.java: [ master, ]
1695:         volatile Thread thread;
406:     static final class ThreadPerTaskExecutor implements Executor {
2647:             public Thread newThread(Runnable r) {
2646:         static final class DaemonThreadFactory implements ThreadFactory {
62:  * <em>non-async</em> methods may be performed by the thread that
69:  * which case, a new Thread is created to run each task).
76:  * class maintains at most one daemon thread for triggering and
174:      *   invocation if already claimed by another thread.
407:         public void execute(Runnable r) { new Thread(r).start(); }
530:          * thread claims ownership.  If async, starts as task -- a
1684:      * Completion for recording and releasing a waiting thread.  This
1698:             this.thread = Thread.currentThread();
1704:             Thread w; // no need to atomically claim
1705:             if ((w = thread) != null) {
1706:                 thread = null;
1712:             if (Thread.interrupted())
1718:                     thread == null);
1729:         final boolean isLive() { return thread != null; }
1761:             q.thread = null;
1766:                     Thread.currentThread().interrupt();
1779:         if (Thread.interrupted())
1805:                 q.thread = null;
1918:      * @throws InterruptedException if the current thread was interrupted
1935:      * @throws InterruptedException if the current thread was interrupted
2420:      * parallel thread, or else an Executor using one thread per async
2422:      * an Executor that provides at least one independent thread.
2648:                 Thread t = new Thread(r);
51:  * <p>When two or more threads attempt to
195:      * linked). Multiple threads can call postComplete, which
203:      * that wake up waiting threads.  The mechanics are similar to
213:      * threads nulling out fields.  We also try to unlink fired
216:      * volatile because they are only visible to other threads upon
403:         ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
1743:                 if (ThreadLocalRandom.nextSecondarySeed() >= 0)
2655:         static final ScheduledThreadPoolExecutor delayer;
2657:             (delayer = new ScheduledThreadPoolExecutor(
2658:                 1, new DaemonThreadFactory())).
github.com/apache/beam:website/www/site/themes/docsy/userguide/package-lock.json: [ master, ]
1098:             "needle": "^2.2.1",
1079:         "needle": {
github.com/google/binnavi:debug/client/windynamorio/drdebug.proto: [ master, ]
347:   optional uint64 thread  = 5; // required
54:     SUSPEND_THREAD        = 9;
55:     RESUME_THREAD         = 10;
75:   repeated uint64 thread_id = 2;
185:     UNKNOWN_THREAD             = 12;
232:   repeated uint64 thread_id = 1;
306:     THREAD_CREATED   = 2;
307:     THREAD_EXITED    = 3;
318:   optional ThreadCreatedInfo   thread_created_info   = 3;
319:   optional ThreadExitedInfo    thread_exited_info    = 4;
330:   optional uint64 thread_id = 3; // required
334:   optional uint64 thread_id = 1; // required
338:   optional uint64 thread_id = 1; // required
357:   optional uint64 thread_id    = 3; // required
365:   optional uint64 thread_id = 1; // required
333: message ThreadCreatedInfo {
337: message ThreadExitedInfo {
84:   optional SuspendThreadArgs       suspend_thread_args        = 9;
85:   optional ResumeThreadArgs        resume_thread_args         = 10;
206:   optional SuspendThreadResult       suspend_thread_result        = 9;
207:   optional ResumeThreadResult        resume_thread_result         = 10;
53:     LIST_THREADS          = 8;
83:   optional ListThreadsArgs         list_threads_args          = 8;
205:   optional ListThreadsResult         list_threads_result          = 8;
118: message ListThreadsArgs {
121: message SuspendThreadArgs {
124: message ResumeThreadArgs {
231: message ListThreadsResult {
235: message SuspendThreadResult {
238: message ResumeThreadResult {
52:     // thread control
74:   //       not all commands could be executed thread-locally (like write memory)
186:     // Someone tried to resume already running thread.
72:   // execute the command only on those threads
github.com/GNOME/gimp:tools/performance-log-viewer.py: [ mainline, ]
285: Thread = namedtuple ("Thread", ("id", "name", "state", "frames"))
744:                 def thread (id, state = None):
734:                 def match_thread (thread, id, state = None):
2930:         def thread_filter_source_get (self):
2933:         def thread_filter_source_set (self, thread_filter):
2940:         def thread_filter_button_toggled (self, button):
275: class ThreadState (enum.Enum):
1955:     class ThreadStore (Gtk.ListStore):
2237:     def threads_row_activated (self, tree, path, col):
2257:     def threads_selection_changed (self, tree_sel):
2433:     class ThreadFilter (Gtk.TreeView):
2557:     class ThreadPopover (Gtk.Popover):
312:             for thread in element.find ("backtrace").iterfind ("thread"):
313:                 id      = thread.get ("id")
314:                 name    = thread.get ("name")
315:                 running = thread.get ("running")
317:                 t = Thread (
325:                 for frame in thread.iterfind ("frame"):
722:             f = eval ("lambda thread, function, %s: %s" % (
737:                              id == thread.id)                 or  \
739:                              thread.name                      and \
740:                              re.fullmatch (id, thread.name))) and \
742:                             re.fullmatch (state, str (thread.state)))
745:                     return any (match_thread (thread, id, state)
746:                                 for thread in samples[i].backtrace or [])
749:                     for thread in samples[i].backtrace or []:
750:                         if match_thread (thread, id, state):
751:                             for frame in thread.frames:
757:                 if f (thread, function, **{
2024:         self.thread_store = store
2028:         self.thread_tree = tree
2205:         sel_rows = self.thread_tree.get_selection ().get_selected_rows ()[1]
2208:             tid = self.thread_store[sel_rows[0]][self.ThreadStore.ID]
2212:         self.thread_store.clear ()
2215:             thread = samples[i].backtrace[t]
2217:             iter = self.thread_store.append (
2218:                 (t, thread.id, thread.name, str (thread.state))
2221:             if thread.id == tid:
2222:                 self.thread_tree.get_selection ().select_iter (iter)
2238:         iter = self.thread_store.get_iter (path)
2240:         tid = self.thread_store[iter][self.ThreadStore.ID]
2245:             threads = filter (lambda thread:
2246:                                 thread.id    == tid and
2247:                                 thread.state == ThreadState.RUNNING,
2298:             for thread in sample.backtrace or []:
2299:                 for frame in thread.frames:
2446:                 threads = list ({thread.id
2448:                                  for thread in sample.backtrace or ()})
2532:             threads = {thread.id: thread.name
2534:                        for thread in samples[i].backtrace or ()}
2574:             thread_filter = ProfileViewer.ThreadFilter ()
2575:             self.thread_filter = thread_filter
2576:             scrolled.add (thread_filter)
2577:             thread_filter.show ()
2640:                 thread_filter_store = popover.thread_filter.store
2642:                 self.thread_filter_store = thread_filter_store
2643:                 self.thread_filter       = thread_filter_store.get_filter ()
2645:                 history.add_source (self.thread_filter_source_get,
2646:                                     self.thread_filter_source_set)
2652:                 button.connect ("toggled", self.thread_filter_button_toggled)
2762:                 for thread in samples[i].backtrace or []:
2763:                     if thread.state in self.thread_filter[thread.id]:
2764:                         thread_frames = thread.frames
2767:                             thread_frames = reversed (thread_frames)
2772:                         for frame in thread_frames:
2931:             return self.thread_filter_store.get_filter ()
2934:             self.thread_filter = thread_filter
2936:             self.thread_filter_store.set_filter (thread_filter)
2942:                 thread_filter = self.thread_filter_store.get_filter ()
2944:                 if thread_filter != self.thread_filter:
2945:                     self.thread_filter = thread_filter
281:             ThreadState.SUSPENDED: "S",
282:             ThreadState.RUNNING:   "R"
320:                     state  = ThreadState.RUNNING if running and int (running) \
321:                              else ThreadState.SUSPENDED,
2012:         header = Gtk.HeaderBar (title = "Threads", has_subtitle = False)
2023:         store = self.ThreadStore ()
2033:         tree.connect ("row-activated", self.threads_row_activated)
2036:                                        self.threads_selection_changed)
2044:         col.add_attribute (cell, "text", self.ThreadStore.ID)
2052:         col.add_attribute (cell, "text", self.ThreadStore.NAME)
2060:         col.add_attribute (cell, "text", self.ThreadStore.STATE)
2250:             if list (threads):
2438:             STATE   = {list (ThreadState)[i]: 3 + i
2439:                        for i in range (len (ThreadState))}
2449:                 threads.sort ()
2451:                 states = [state == ThreadState.RUNNING for state in self.STATE]
2453:                 for id in threads:
2539:                 if id in threads:
2541:                     row[self.store.NAME]    = threads[id]
2638:                 popover = ProfileViewer.ThreadPopover ()
2659:                 label = Gtk.Label (label = "Threads")
github.com/google/guava:guava/src/com/google/common/util/concurrent/AbstractFuture.java: [ master, ]
204:     @CheckForNull volatile Thread thread;
1291:     abstract void putThread(Waiter waiter, Thread newValue);
1364:     void putThread(Waiter waiter, Thread newValue) {
1416:     void putThread(Waiter waiter, Thread newValue) {
1450:     void putThread(Waiter waiter, Thread newValue) {
1320:     static final long WAITER_THREAD_OFFSET;
1396:     final AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater;
170:                 newUpdater(Waiter.class, Thread.class, "thread"),
215:       ATOMIC_HELPER.putThread(this, Thread.currentThread());
226:       // unpark even though the thread has already removed itself from the list. But even if we did
228:       Thread w = thread;
230:         thread = null;
242:    *   <li>This is only called when a waiting thread times out or is interrupted. Both of which
248:     node.thread = null; // mark as 'deleted'
259:         if (curr.thread != null) { // we aren't unlinking this node, update pred.
263:           if (pred.thread == null) { // We raced with another node that unlinked pred. Restart.
404:   //   have observed 12 micros on 64 bit linux systems to wake up a parked thread). So if the
421:    * current thread is interrupted during the call, even if the value is already available.
434:     if (Thread.interrupted()) {
454:               if (Thread.interrupted()) {
469:                 // Remove the waiter, one way or another we are done parking this thread.
490:       if (Thread.interrupted()) {
534:    * current thread is interrupted during the call, even if the value is already available.
542:     if (Thread.interrupted()) {
559:             if (Thread.interrupted()) {
987:         Thread.currentThread().interrupt();
1256:     // arbitrary cycles using a thread local but this should be a good enough solution (it is also
1290:     /** Non volatile write of the thread to the {@link Waiter#thread} field. */
1354:         WAITER_THREAD_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("thread"));
1365:       UNSAFE.putObject(waiter, WAITER_THREAD_OFFSET, newValue);
1403:         AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater,
1451:       waiter.thread = newValue;
387:   /** All waiting threads. */
992:   /** Unblocks all threads and runs all listeners. */
1109:   /** Releases all threads in the {@link #waiters} list, and clears the list. */
1408:       this.waiterThreadUpdater = waiterThreadUpdater;
1417:       waiterThreadUpdater.lazySet(waiter, newValue);
github.com/google/guava:android/guava/src/com/google/common/util/concurrent/AbstractFuture.java: [ master, ]
204:     @CheckForNull volatile Thread thread;
1291:     abstract void putThread(Waiter waiter, Thread newValue);
1364:     void putThread(Waiter waiter, Thread newValue) {
1416:     void putThread(Waiter waiter, Thread newValue) {
1450:     void putThread(Waiter waiter, Thread newValue) {
1320:     static final long WAITER_THREAD_OFFSET;
1396:     final AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater;
170:                 newUpdater(Waiter.class, Thread.class, "thread"),
215:       ATOMIC_HELPER.putThread(this, Thread.currentThread());
226:       // unpark even though the thread has already removed itself from the list. But even if we did
228:       Thread w = thread;
230:         thread = null;
242:    *   <li>This is only called when a waiting thread times out or is interrupted. Both of which
248:     node.thread = null; // mark as 'deleted'
259:         if (curr.thread != null) { // we aren't unlinking this node, update pred.
263:           if (pred.thread == null) { // We raced with another node that unlinked pred. Restart.
404:   //   have observed 12 micros on 64 bit linux systems to wake up a parked thread). So if the
421:    * current thread is interrupted during the call, even if the value is already available.
434:     if (Thread.interrupted()) {
454:               if (Thread.interrupted()) {
469:                 // Remove the waiter, one way or another we are done parking this thread.
490:       if (Thread.interrupted()) {
534:    * current thread is interrupted during the call, even if the value is already available.
542:     if (Thread.interrupted()) {
559:             if (Thread.interrupted()) {
987:         Thread.currentThread().interrupt();
1256:     // arbitrary cycles using a thread local but this should be a good enough solution (it is also
1290:     /** Non volatile write of the thread to the {@link Waiter#thread} field. */
1354:         WAITER_THREAD_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("thread"));
1365:       UNSAFE.putObject(waiter, WAITER_THREAD_OFFSET, newValue);
1403:         AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater,
1451:       waiter.thread = newValue;
387:   /** All waiting threads. */
992:   /** Unblocks all threads and runs all listeners. */
1109:   /** Releases all threads in the {@link #waiters} list, and clears the list. */
1408:       this.waiterThreadUpdater = waiterThreadUpdater;
1417:       waiterThreadUpdater.lazySet(waiter, newValue);
github.com/google/binnavi:debug/client/defs.hpp: [ master, ]
232: struct Thread {
247:   Thread(unsigned int tid, ThreadState state)
136: enum ThreadState {
264:   typedef std::function<bool(const Thread&)> ThreadComparator;
586:   std::vector<Thread> threads;
589:   void addThread(const Thread& thread) {
158:   dbgevt_thread_created,
161:   dbgevt_thread_closed,
266:   static ThreadComparator MakeThreadIdComparator(int tid) {
593:   std::vector<Thread> getThreads() const {
135: // Identifies the state of a thread
137:   // Thread is running
140:   // Thread is suspended
157:   // A new thread was created in the target process
160:   // An existing thread was closed in the target process
230:  * Describes a thread of the target process
233:   //  The thread ID of the thread
236:   // The state of the thread
242:    * Creates a new Thread object
244:    * @param tid The thread ID of the thread
245:    * @param state The state of the thread
252:   bool operator==(const Thread& rhs) const {
256:   bool operator<(const Thread& rhs) const {
261:    * Returns a function which matches the thread with a given id
267:     return [tid](const Thread& t)->bool {return t.tid == tid; };
414:   // Thread ID of the thread where the exception happened
590:     threads.push_back(thread);
717:       std::vector<Thread> threads = registers.getThreads();
719:       for (std::vector<Thread>::iterator Iter = threads.begin();
721:         Thread t = *Iter;
237:   ThreadState state;
594:     return threads;
720:           Iter != threads.end(); ++Iter) {
github.com/GoogleCloudPlatform/training-data-analyst:blogs/microservices-demo-1/src/paymentservice/package-lock.json: [ master, ]
1058:             "needle": "^2.2.0",
1043:         "needle": {
github.com/GoogleCloudPlatform/training-data-analyst:blogs/microservices-demo-1/src/currencyservice/package-lock.json: [ master, ]
1036:             "needle": "^2.2.0",
1021:         "needle": {
github.com/kubernetes/website:themes/docsy/userguide/package-lock.json: [ master, ] Duplicate result
github.com/GNOME/gimp:app/widgets/gimpdashboard.c: [ mainline, ]
299:   GThread                      *thread;
146:   VARIABLE_ASSIGNED_THREADS,
147:   VARIABLE_ACTIVE_THREADS,
1254:   /* sampler thread
1256:    * we use a separate thread for sampling, so that data is sampled even when
1257:    * the main thread is busy
1259:   priv->thread = g_thread_new ("dashboard",
1374:   if (priv->thread)
1383:       g_clear_pointer (&priv->thread, g_thread_join);
3660:       gint     thread;
3681:           for (thread = 0; thread < n_threads; thread++)
3683:               guintptr thread_id;
3685:               thread_id = gimp_backtrace_get_thread_id (priv->log_backtrace,
3686:                                                         thread);
3688:               if (gimp_backtrace_find_thread_by_id (backtrace,
3689:                                                     thread_id, thread) < 0)
3691:                   const gchar *thread_name;
3695:                   thread_name =
3696:                     gimp_backtrace_get_thread_name (priv->log_backtrace,
3697:                                                     thread);
3700:                                              "<thread id=\"%llu\"",
3701:                                              (unsigned long long) thread_id);
3703:                   if (thread_name)
3707:                       gimp_dashboard_log_print_escaped (dashboard, thread_name);
3720:       for (thread = 0; thread < n_threads; thread++)
3722:           guintptr     thread_id;
3723:           const gchar *thread_name;
3732:           thread_id   = gimp_backtrace_get_thread_id     (backtrace, thread);
3733:           thread_name = gimp_backtrace_get_thread_name   (backtrace, thread);
3735:           running     = gimp_backtrace_is_thread_running (backtrace, thread);
3736:           n_frames    = gimp_backtrace_get_n_frames      (backtrace, thread);
3740:               gint other_thread = gimp_backtrace_find_thread_by_id (
3741:                 priv->log_backtrace, thread_id, thread);
3743:               if (other_thread >= 0)
3748:                   last_running  = gimp_backtrace_is_thread_running (
3749:                     priv->log_backtrace, other_thread);
3751:                     priv->log_backtrace, other_thread);
3758:                                                             thread, i) !=
3760:                                                             other_thread, i))
3772:                                                             thread, -i - 1) !=
3774:                                                             other_thread, -i - 1))
3794:                                      "<thread id=\"%llu\"",
3795:                                      (unsigned long long) thread_id);
3797:           if (thread_name)
3801:               gimp_dashboard_log_print_escaped (dashboard, thread_name);
3834:                                                               thread, frame);
3844:                                          "</thread>\n");
694:   [VARIABLE_ASSIGNED_THREADS] =
695:   { .name             = "assigned-threads",
697:     .description      = N_("Number of assigned worker threads"),
700:     .data             = "assigned-threads"
703:   [VARIABLE_ACTIVE_THREADS] =
704:   { .name             = "active-threads",
706:     .description      = N_("Number of active worker threads"),
709:     .data             = "active-threads"
949:                           { .variable       = VARIABLE_ASSIGNED_THREADS,
952:                           { .variable       = VARIABLE_ACTIVE_THREADS,
3659:       gint     n_threads;
3679:           n_threads = gimp_backtrace_get_n_threads (priv->log_backtrace);
3718:       n_threads = gimp_backtrace_get_n_threads (backtrace);
1260:                                (GThreadFunc) gimp_dashboard_sample,
github.com/google/gapid:gapis/service/service.proto: [ master, ]
101:     Thread thread = 18;
892: message Thread {
78: message Threads {
102:     Threads threads = 19;
79:   repeated path.Thread list = 1;
891: // Thread represents a single thread in the capture.
github.com/apache/pdfbox:pdfbox/src/main/java/org/apache/pdfbox/cos/COSName.java: [ trunk, ]
573:     public static final COSName THREAD = new COSName("Thread");
574:     public static final COSName THREADS = new COSName("Threads");
35:     // using ConcurrentHashMap because this can be accessed by multiple threads
github.com/tensorflow/tfjs:.vscode/settings.json: [ master, ]
109:     "thread": "cpp",
129:     "__threading_support": "cpp",
github.com/libgit2/objective-git:External/libgit2/src/pack-objects.c: [ master, ]
1110: 	git_thread thread;
1109: struct thread_params {
1127: static void *threaded_find_deltas(void *arg)
183: unsigned int git_packbuilder_set_threads(git_packbuilder *pb, unsigned int n)
15: #include "thread-utils.h"
155: 	pb->nr_threads = 1; /* do not spawn any thread by default */
1129: 	struct thread_params *me = arg;
1143: 			git_error_set(GIT_ERROR_THREAD, "unable to lock packfile condition mutex");
1152: 		 * condition because the main thread may have set it to 1
1155: 		 * was initialized to 0 before this thread was spawned
1168: 	struct thread_params *p;
1219: 		ret = git_thread_create(&p[i].thread,
1222: 			git_error_set(GIT_ERROR_THREAD, "unable to create thread");
1229: 	 * Now let's wait for work completion.  Each time a thread is done
1231: 	 * thread with the largest number of unprocessed objects and give
1232: 	 * it to that newly idle thread.  This ensure good load balancing
1237: 		struct thread_params *target = NULL;
1238: 		struct thread_params *victim = NULL;
1241: 		/* Start by locating a thread that has transitioned its
1256: 		 * a thread to receive more work. We still need to locate a
1257: 		 * thread from which to steal work (the victim). */
1291: 			git_error_set(GIT_ERROR_THREAD, "unable to lock packfile condition mutex");
1301: 			git_thread_join(&target->thread, NULL);
50: #ifdef GIT_THREADS
62: #endif /* GIT_THREADS */
163: #ifdef GIT_THREADS
187: #ifdef GIT_THREADS
188: 	pb->nr_threads = n;
191: 	assert(1 == pb->nr_threads);
194: 	return pb->nr_threads;
1033: 		 * it anyway, and doing it here while we're threaded will
1034: 		 * save a lot of time in the non threaded write phase,
1107: #ifdef GIT_THREADS
1170: 	int ret, active_threads = 0;
1172: 	if (!pb->nr_threads)
1173: 		pb->nr_threads = git_online_cpus();
1175: 	if (pb->nr_threads <= 1) {
1180: 	p = git__mallocarray(pb->nr_threads, sizeof(*p));
1183: 	/* Partition the work among the threads */
1184: 	for (i = 0; i < pb->nr_threads; ++i) {
1185: 		size_t sub_size = list_size / (pb->nr_threads - i);
1188: 		if (sub_size < 2*window && i+1 < pb->nr_threads)
1211: 	/* Start work threads */
1212: 	for (i = 0; i < pb->nr_threads; ++i) {
1220: 					threaded_find_deltas, &p[i]);
1225: 		active_threads++;
1236: 	while (active_threads) {
1247: 			for (i = 0; !target && i < pb->nr_threads; i++)
1258: 		for (i = 0; i < pb->nr_threads; i++)
1304: 			active_threads--;
1773: #ifdef GIT_THREADS
github.com/googleapis/google-cloud-ruby:google-cloud-debugger/lib/google/cloud/debugger/breakpoint/evaluator.rb: [ master, ]
169:             Thread => hashify(
549:             Thread => hashify(
548:             ThreadGroup => hashify(%I[enclosed? list]).freeze,
193:               %I[disable_method_trace_for_thread]
567:                 thread_variable?
568:                 thread_variable_get
569:                 thread_variables
764:             Thread.current.thread_variable_get EVALUATOR_REFERENCE
835:           # context binding. The evaluation is done in a separate thread due
837:           # addtional code tracing is disabled in original thread.
849:             # do evaluation in a new thread, where function calls can be
851:             thr = Thread.new do
852:               Thread.current.thread_variable_set EVALUATOR_REFERENCE, self
868:             # Force terminate evaluation thread if not finished already and
946:                   :enable_method_trace_for_thread)
950:                   :disable_method_trace_for_thread)
1018:               :disable_method_trace_for_thread
github.com/apache/httpcomponents-client:httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java: [ master, ]
849:         private final Thread thread;
206:     private ThreadFactory threadFactory;
427:     public final H2AsyncClientBuilder setThreadFactory(final ThreadFactory threadFactory) {
568:      * connection pool using a background thread.
571:      * in order to stop and release the background thread.
852:             this.thread = new DefaultThreadFactory("idle-connection-evictor", true).newThread(() -> {
854:                     while (!Thread.currentThread().isInterrupted()) {
859:                     Thread.currentThread().interrupt();
867:             thread.start();
871:             thread.interrupt();
38: import java.util.concurrent.ThreadFactory;
425:      * Assigns {@link ThreadFactory} instance.
428:         this.threadFactory = threadFactory;
735:                 threadFactory != null ? threadFactory : new DefaultThreadFactory("httpclient-dispatch", true),
832:                 threadFactory != null ? threadFactory : new DefaultThreadFactory("httpclient-main", true),
76: import org.apache.hc.core5.concurrent.DefaultThreadFactory;
android.googlesource.com/platform/external/rust/crates/memchr:src/memmem/mod.rs: [ master, ]
520:     pub fn needle(&self) -> &[u8] {
651:     pub fn needle(&self) -> &[u8] {
712:     needle: CowBytes<'n>,
836:     fn needle(&self) -> &[u8] {
1006:     needle: CowBytes<'n>,
1045:     fn needle(&self) -> &[u8] {
730: pub(crate) struct NeedleInfo {
987: impl NeedleInfo {
7: the empty needle, the standard library reports matches only at valid UTF-8
51: # Example: repeating a search for the same needle
54: measurable in some workloads. In cases where the same needle is used to search
103:                 needle: Vec<u8>
105:                 proptests::matches_naive(false, &haystack, &needle, $fwd)
118:                 needle: Vec<u8>
120:                 proptests::matches_naive(true, &haystack, &needle, $rev)
167: /// with respect to both the needle and the haystack. That is, this runs
168: /// in `O(needle.len() + haystack.len())` time.
190:     needle: &'n N,
192:     FindIter::new(haystack, Finder::new(needle))
201: /// with respect to both the needle and the haystack. That is, this runs
202: /// in `O(needle.len() + haystack.len())` time.
224:     needle: &'n N,
226:     FindRevIter::new(haystack, FinderRev::new(needle))
229: /// Returns the index of the first occurrence of the given needle.
231: /// Note that if you're are searching for the same needle in many different
238: /// with respect to both the needle and the haystack. That is, this runs
239: /// in `O(needle.len() + haystack.len())` time.
257: pub fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
259:         rabinkarp::find(haystack, needle)
261:         Finder::new(needle).find(haystack)
265: /// Returns the index of the last occurrence of the given needle.
267: /// Note that if you're are searching for the same needle in many different
274: /// with respect to both the needle and the haystack. That is, this runs
275: /// in `O(needle.len() + haystack.len())` time.
294: pub fn rfind(haystack: &[u8], needle: &[u8]) -> Option<usize> {
296:         rabinkarp::rfind(haystack, needle)
298:         FinderRev::new(needle).rfind(haystack)
307: /// needle.
342:                 self.pos = pos + core::cmp::max(1, self.finder.needle().len());
354: /// needle.
359:     /// When searching with an empty needle, this gets set to `None` after
398: /// A single substring searcher fixed to a particular needle.
403: /// concern when it's necessary to re-use the same needle to search multiple
410: /// the lifetime of its needle.
417:     /// Create a new finder for the given needle.
419:     pub fn new<B: ?Sized + AsRef<[u8]>>(needle: &'n B) -> Finder<'n> {
420:         FinderBuilder::new().build_forward(needle)
423:     /// Returns the index of the first occurrence of this needle in the given
429:     /// with respect to both the needle and the haystack. That is, this runs
430:     /// in `O(needle.len() + haystack.len())` time.
456:     /// with respect to both the needle and the haystack. That is, this runs
457:     /// in `O(needle.len() + haystack.len())` time.
486:     /// borrows the needle.
489:     /// this copies the needle.
505:     /// needle itself. Namely, a finder's needle can be either borrowed or
506:     /// owned, so the lifetime of the needle returned must necessarily be the
513:     /// Returns the needle that this finder searches for.
515:     /// Note that the lifetime of the needle returned is tied to the lifetime
517:     /// finder's needle can be either borrowed or owned, so the lifetime of the
518:     /// needle returned must necessarily be the shorter of the two.
521:         self.searcher.needle()
525: /// A single substring reverse searcher fixed to a particular needle.
530: /// concern when it's necessary to re-use the same needle to search multiple
537: /// the lifetime of its needle.
544:     /// Create a new reverse finder for the given needle.
546:     pub fn new<B: ?Sized + AsRef<[u8]>>(needle: &'n B) -> FinderRev<'n> {
547:         FinderBuilder::new().build_reverse(needle)
550:     /// Returns the index of the last occurrence of this needle in the given
559:     /// with respect to both the needle and the haystack. That is, this runs
560:     /// in `O(needle.len() + haystack.len())` time.
587:     /// with respect to both the needle and the haystack. That is, this runs
588:     /// in `O(needle.len() + haystack.len())` time.
617:     /// borrows the needle.
620:     /// this copies the needle.
636:     /// needle itself. Namely, a finder's needle can be either borrowed or
637:     /// owned, so the lifetime of the needle returned must necessarily be the
644:     /// Returns the needle that this finder searches for.
646:     /// Note that the lifetime of the needle returned is tied to the lifetime
648:     /// finder's needle can be either borrowed or owned, so the lifetime of the
649:     /// needle returned must necessarily be the shorter of the two.
652:         self.searcher.needle()
672:     /// Build a forward finder using the given needle from the current
676:         needle: &'n B,
678:         Finder { searcher: Searcher::new(self.config, needle.as_ref()) }
681:     /// Build a reverse finder using the given needle from the current
685:         needle: &'n B,
687:         FinderRev { searcher: SearcherRev::new(needle.as_ref()) }
703: /// variety of parameters (CPU support, target, needle size, haystack size and
708:     /// The actual needle we're searching for.
713:     /// A collection of facts computed on the needle that are useful for more
725: /// A collection of facts computed about a search needle.
731:     /// The offsets of "rare" bytes detected in the needle.
735:     /// one or two bytes. If we pick bytes from the needle that occur
742:     /// A Rabin-Karp hash of the needle.
764:     /// A special case for empty needles. An empty needle always matches, even
767:     /// This is used whenever the needle is a single byte. In this case, we
771:     /// linear time guarantee. In general, it's used when the needle is bigger
782:     fn new(config: SearcherConfig, needle: &'n [u8]) -> Searcher<'n> {
785:         let ninfo = NeedleInfo::new(needle);
787:             prefilter::forward(&config.prefilter, &ninfo.rarebytes, needle);
788:         let kind = if needle.len() == 0 {
790:         } else if needle.len() == 1 {
791:             OneByte(needle[0])
792:         } else if let Some(fwd) = x86::avx::Forward::new(&ninfo, needle) {
794:         } else if let Some(fwd) = x86::sse::Forward::new(&ninfo, needle) {
797:             TwoWay(twoway::Forward::new(needle))
799:         Searcher { needle: CowBytes::new(needle), ninfo, prefn, kind }
803:     fn new(config: SearcherConfig, needle: &'n [u8]) -> Searcher<'n> {
806:         let ninfo = NeedleInfo::new(needle);
808:             prefilter::forward(&config.prefilter, &ninfo.rarebytes, needle);
809:         let kind = if needle.len() == 0 {
811:         } else if needle.len() == 1 {
812:             OneByte(needle[0])
814:             TwoWay(twoway::Forward::new(needle))
816:         Searcher { needle: CowBytes::new(needle), ninfo, prefn, kind }
837:         self.needle.as_slice()
861:             needle: CowBytes::new(self.needle()),
890:             needle: self.needle.into_owned(),
908:         let needle = self.needle();
909:         if haystack.len() < needle.len() {
918:                 if rabinkarp::is_fast(haystack, needle) {
919:                     rabinkarp::find_with(&self.ninfo.nhash, haystack, needle)
921:                     self.find_tw(tw, state, haystack, needle)
933:                     rabinkarp::find_with(&self.ninfo.nhash, haystack, needle)
935:                     gs.find(haystack, needle)
947:                     rabinkarp::find_with(&self.ninfo.nhash, haystack, needle)
949:                     gs.find(haystack, needle)
955:     /// Calls Two-Way on the given haystack/needle.
970:         needle: &[u8],
980:                 return tw.find(Some(&mut pre), haystack, needle);
983:         tw.find(None, haystack, needle)
988:     pub(crate) fn new(needle: &[u8]) -> NeedleInfo {
990:             rarebytes: RareNeedleBytes::forward(needle),
991:             nhash: NeedleHash::forward(needle),
1005:     /// The actual needle we're searching for.
1007:     /// A Rabin-Karp hash of the needle.
1015:     /// A special case for empty needles. An empty needle always matches, even
1018:     /// This is used whenever the needle is a single byte. In this case, we
1022:     /// linear time guarantee. In general, it's used when the needle is bigger
1028:     fn new(needle: &'n [u8]) -> SearcherRev<'n> {
1031:         let kind = if needle.len() == 0 {
1033:         } else if needle.len() == 1 {
1034:             OneByte(needle[0])
1036:             TwoWay(twoway::Reverse::new(needle))
1039:             needle: CowBytes::new(needle),
1040:             nhash: NeedleHash::reverse(needle),
1046:         self.needle.as_slice()
1058:             needle: CowBytes::new(self.needle()),
1074:             needle: self.needle.into_owned(),
1087:         let needle = self.needle();
1088:         if haystack.len() < needle.len() {
1097:                 if rabinkarp::is_fast(haystack, needle) {
1098:                     rabinkarp::rfind_with(&self.nhash, haystack, needle)
1100:                     tw.rfind(haystack, needle)
1164:         needle: &[u8],
1168:             naive_rfind(haystack, needle) == search(haystack, needle)
1170:             naive_find(haystack, needle) == search(haystack, needle)
1174:     /// Naively search forwards for the given needle in the given haystack.
1175:     fn naive_find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1176:         if needle.is_empty() {
1178:         } else if haystack.len() < needle.len() {
1181:         for i in 0..(haystack.len() - needle.len() + 1) {
1182:             if needle == &haystack[i..i + needle.len()] {
1189:     /// Naively search in reverse for the given needle in the given haystack.
1190:     fn naive_rfind(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1191:         if needle.is_empty() {
1193:         } else if haystack.len() < needle.len() {
1196:         for i in (0..(haystack.len() - needle.len() + 1)).rev() {
1197:             if needle == &haystack[i..i + needle.len()] {
1212:     /// Each test is a (needle, haystack, expected_fwd, expected_rev) tuple.
1258:     /// accepts a haystack and a needle and returns the starting position
1259:     /// of the first occurrence of needle in the haystack, or `None` if one
1264:         for &(needle, haystack, expected_fwd, _) in SEARCH_TESTS {
1265:             let (n, h) = (needle.as_bytes(), haystack.as_bytes());
1269:                 "needle: {:?}, haystack: {:?}, expected: {:?}",
1278:     /// accepts a haystack and a needle and returns the starting position of
1279:     /// the last occurrence of needle in the haystack, or `None` if one doesn't
1284:         for &(needle, haystack, _, expected_rev) in SEARCH_TESTS {
1285:             let (n, h) = (needle.as_bytes(), haystack.as_bytes());
1289:                 "needle: {:?}, haystack: {:?}, expected: {:?}",
5: arbitrary bytes. For all non-empty needles, these routines will report exactly
75:         rabinkarp::NeedleHash,
715:     ninfo: NeedleInfo,
751:     pub(crate) nhash: NeedleHash,
989:         NeedleInfo {
1008:     nhash: NeedleHash,
76:         rarebytes::RareNeedleBytes,
741:     pub(crate) rarebytes: RareNeedleBytes,
android.googlesource.com/platform/external/opencv3:samples/gpu/stereo_multi.cpp: [ master, ]
31: class Thread
53:     Thread(void (*func)(void* userData), void* userData)
78: class Thread
99:     Thread(void (*func)(void* userData), void* userData)
49:     HANDLE thread_;
67:     ~Thread()
107:     ~Thread()
50:     DWORD threadId_;
95:     pthread_t thread_;
167: class StereoMultiGpuThread
196: StereoMultiGpuThread::StereoMultiGpuThread()
205: StereoMultiGpuThread::~StereoMultiGpuThread()
39:     static DWORD WINAPI WinThreadFunction(LPVOID lpParam)
86:     static void* PThreadFunction(void* lpParam)
27: // Thread
58:         thread_ = CreateThread(
61:             WinThreadFunction,      // thread function name
62:             &userData_,             // argument to thread function
64:             &threadId_);            // returns the thread identifier
69:         CloseHandle(thread_);
74:         WaitForSingleObject(thread_, INFINITE);
104:         pthread_create(&thread_, NULL, PThreadFunction, &userData_);
109:         pthread_detach(thread_);
114:         pthread_join(thread_, NULL);
249:     Thread thread0(launchGpuStereoAlg, &launchDatas[0]);
250:     Thread thread1(launchGpuStereoAlg, &launchDatas[1]);
252:     thread0.wait();
253:     thread1.wait();
273: // Run Stereo algorithm on two GPUs from single host thread using async API
426:     cout << "| Frame | GPU 0 ms | GPU 1 ms | Multi Thread ms | Multi Stream ms |" << endl;
8:     #include <pthread.h>
28: // OS-specific wrappers for multi-threading
164: // StereoMultiGpuThread
165: // Run Stereo algorithm on two GPUs using different host threads
170:     StereoMultiGpuThread();
171:     ~StereoMultiGpuThread();
220: void StereoMultiGpuThread::compute(const Mat& leftFrame, const Mat& rightFrame, Mat& disparity)
256: void StereoMultiGpuThread::launchGpuStereoAlg(void* userData)
410:     StereoMultiGpuThread multiThreadAlg;
415:     Mat disparityMultiThread;
465:                                disparityMultiThread);
484:         resize(disparityMultiThread, disparityMultiThreadShow, Size(1024, 768), 0, 0, INTER_AREA);
489:         imshow("disparityMultiThread", disparityMultiThreadShow);
420:     Mat disparityMultiThreadShow;
464:         multiThreadAlg.compute(leftGrayFrame.createMatHeader(), rightGrayFrame.createMatHeader(),
468:         const double multiThreadTime = tm.getTimeMilli();
479:              << setw(15) << setprecision(1) << fixed << multiThreadTime << " | "
android.googlesource.com/platform/external/perfetto:protos/perfetto/trace/perfetto_trace.proto: [ master, ]
2897:   optional int32 thread = 2;
8230:   message Thread {
8299:   message Thread {
8923:   optional ThreadDescriptor thread = 4;
566:   optional uint32 thread_time_in_state_cache_size = 8;
2532:   optional int32 thread_id = 4;
2534:   optional int64 thread_duration = 6;
2540:   optional int64 thread_timestamp = 12;
2887:   optional int32 to_thread = 4;
6637:     REASON_MAIN_THREAD = 2;
6658:     SCROLL_MAIN_THREAD = 1;
6659:     SCROLL_COMPOSITOR_THREAD = 2;
7185:   oneof thread_time {
7191:     int64 thread_time_delta_us = 2;
7194:     int64 thread_time_absolute_us = 17;
7201:   oneof thread_instruction_count {
7203:     int64 thread_instruction_count_delta = 8;
7204:     int64 thread_instruction_count_absolute = 20;
7221:     optional int64 thread_duration_us = 4;
7224:     optional int64 thread_instruction_delta = 15;
7259:       SCOPE_THREAD = 3;
7523:   optional uint32 thread_id = 5;
8592:   optional string thread_name = 5;
8727:     THREAD_UNSPECIFIED = 0;
8729:     THREAD_MAIN = 1;
8730:     THREAD_IO = 2;
8732:     THREAD_POOL_BG_WORKER = 3;
8733:     THREAD_POOL_FG_WORKER = 4;
8734:     THREAD_POOL_FG_BLOCKING = 5;
8735:     THREAD_POOL_BG_BLOCKING = 6;
8736:     THREAD_POOL_SERVICE = 7;
8738:     THREAD_COMPOSITOR = 8;
8739:     THREAD_VIZ_COMPOSITOR = 9;
8740:     THREAD_COMPOSITOR_WORKER = 10;
8742:     THREAD_SERVICE_WORKER = 11;
8743:     THREAD_NETWORK_SERVICE = 12;
8745:     THREAD_CHILD_IO = 13;
8746:     THREAD_BROWSER_IO = 14;
8748:     THREAD_BROWSER_MAIN = 15;
8749:     THREAD_RENDERER_MAIN = 16;
8750:     THREAD_UTILITY_MAIN = 17;
8751:     THREAD_GPU_MAIN = 18;
8753:     THREAD_CACHE_BLOCKFILE = 19;
8754:     THREAD_MEDIA = 20;
8755:     THREAD_AUDIO_OUTPUTDEVICE = 21;
8756:     THREAD_AUDIO_INPUTDEVICE = 22;
8757:     THREAD_GPU_MEMORY = 23;
8758:     THREAD_GPU_VSYNC = 24;
8759:     THREAD_DXA_VIDEODECODER = 25;
8760:     THREAD_BROWSER_WATCHDOG = 26;
8761:     THREAD_WEBRTC_NETWORK = 27;
8762:     THREAD_WINDOW_OWNER = 28;
8763:     THREAD_WEBRTC_SIGNALING = 29;
8764:     THREAD_WEBRTC_WORKER = 30;
8765:     THREAD_PPAPI_MAIN = 31;
8766:     THREAD_GPU_WATCHDOG = 32;
8767:     THREAD_SWAPPER = 33;
8768:     THREAD_GAMEPAD_POLLING = 34;
8769:     THREAD_WEBCRYPTO = 35;
8770:     THREAD_DATABASE = 36;
8771:     THREAD_PROXYRESOLVER = 37;
8772:     THREAD_DEVTOOLSADB = 38;
8773:     THREAD_NETWORKCONFIGWATCHER = 39;
8774:     THREAD_WASAPI_RENDER = 40;
8776:     THREAD_MEMORY_INFRA = 50;
8777:     THREAD_SAMPLING_PROFILER = 51;
8780:   optional ThreadType thread_type = 1;
8924:   optional ChromeThreadDescriptor chrome_thread = 7;
9087:     ThreadDescriptor thread_descriptor = 44;
8263:     repeated Thread threads = 11;
8325:     repeated Thread threads_deprecated = 4 [deprecated = true];
8339:   repeated Thread threads = 2;
8588: message ThreadDescriptor {
8726:   enum ThreadType {
541:   optional bool record_thread_names = 3;
562:   optional bool record_thread_time_in_state = 7;
6490:     optional bool main_thread_missed_last_deadline = 34;
6714:     STEP_MAIN_THREAD_SCROLL_UPDATE = 2;
7742:     ROOT_THREAD_BLOCK = 6;
7744:     ROOT_THREAD_OBJECT = 8;
8100:     UNWIND_ERROR_THREAD_TIMEOUT = 10;
8101:     UNWIND_ERROR_THREAD_DOES_NOT_EXIST = 11;
8599:     CHROME_THREAD_UNSPECIFIED = 0;
8601:     CHROME_THREAD_MAIN = 1;
8602:     CHROME_THREAD_IO = 2;
8605:     CHROME_THREAD_POOL_BG_WORKER = 3;
8606:     CHROME_THREAD_POOL_FG_WORKER = 4;
8607:     CHROME_THREAD_POOL_FB_BLOCKING = 5;
8608:     CHROME_THREAD_POOL_BG_BLOCKING = 6;
8609:     CHROME_THREAD_POOL_SERVICE = 7;
8612:     CHROME_THREAD_COMPOSITOR = 8;
8613:     CHROME_THREAD_VIZ_COMPOSITOR = 9;
8614:     CHROME_THREAD_COMPOSITOR_WORKER = 10;
8617:     CHROME_THREAD_SERVICE_WORKER = 11;
8620:     CHROME_THREAD_MEMORY_INFRA = 50;
8621:     CHROME_THREAD_SAMPLING_PROFILER = 51;
8623:   optional ChromeThreadType chrome_thread_type = 4;
8633:   optional int64 reference_thread_time_us = 7;
8634:   optional int64 reference_thread_instruction_count = 8;
8815:     COUNTER_THREAD_TIME_NS = 1;
8818:     COUNTER_THREAD_INSTRUCTION_COUNT = 2;
8598:   enum ChromeThreadType {
8725: message ChromeThreadDescriptor {
539:   // If enabled thread names are also recoded (this is redundant if sched_switch
564:   // Size of the cache for thread time_in_state cpu freq values.
6611:     // from both the compositor thread and main-threads were handled).
6615:     // (e.g. missed updates from the main-thread, but included updates from the
6616:     // compositor thread).
6634:     // Frame was dropped because of the main-thread.
6635:     // The main-thread may cause a frame to be dropped, e.g. if the main-thread
6668:   // If any main thread animation is active during this frame.
6670:   // If any compositor thread animation is active during this frame.
6707:     // Emitted on the browser main thread.
6712:     // Occurs on the Renderer's main thread.
6725:     // Happens on the GPU main thread after the swap has completed.
6925: // which describe activity on a track, such as a thread or asynchronous event
6941: // To associate an event with a custom track (e.g. a thread), the track is
6949: //       // Optionally, associate the track with a thread.
6950: //       thread_descriptor {
7047:   // sequence (in most cases sequence = one thread). If no value is specified
7075:   // For example, this allows snapshotting the thread time clock at each
7076:   // thread-track BEGIN and END event to capture the cpu time delta of a slice.
7088:   // an input event may be handled on one thread but cause another event on
7089:   // a different thread - a flow between the two events can associate them.
7181:   // encode thread time instead.
7183:   // CPU time for the current thread (e.g., CLOCK_THREAD_CPUTIME_ID) in
7198:   // encode thread instruction count instead.
7200:   // Value of the instruction counter for the current thread.
7202:     // Same encoding as |thread_time| field above.
7207:   // Apart from {category, time, thread time, tid, pid}, other legacy trace
7237:     // Consider the thread timestamps for async BEGIN/END event pairs as valid.
7264:     // another process/thread. This should be the exception. Normally, the
7522:   // ID of the thread that emitted the event.
7875: //   samples for a Chromium thread.
8222: // they are dumped at a different rate than cmdline and thread list.
8227:   // Per-thread periodically sampled stats.
8298:   // Representation of a thread.
8300:     // The thread id (as per gettid())
8303:     // Thread group id (i.e. the PID of the process, == TID of the main thread)
8306:     // The name of the thread.
8312:     // The UNIX process ID, aka thread group ID (as per getpid()).
8319:     // If it is a kernel thread there will only be one cmdline field
8333:   // different ProcessTree messages. A thread might event not show up at all, if
8544: // usually by the process's main thread.
8582: // Begin of protos/perfetto/trace/track_event/thread_descriptor.proto
8584: // Describes a thread's attributes. Emitted as part of a TrackDescriptor,
8585: // usually by the thread's trace writer.
8636:   // To support old UI. New UI should determine default sorting by thread_type.
8640: // End of protos/perfetto/trace/track_event/thread_descriptor.proto
8718: // Begin of protos/perfetto/trace/track_event/chrome_thread_descriptor.proto
8720: // Describes a Chrome thread's attributes. Emitted as part of a TrackDescriptor,
8721: // usually by the thread's trace writer. Must be paired with a ThreadDescriptor
8782:   // To support old UI. New UI should determine default sorting by thread_type.
8786: // End of protos/perfetto/trace/track_event/chrome_thread_descriptor.proto
8790: // Defines properties of a counter track, e.g. for built-in counters (thread
8811:     // Thread-scoped counters. The thread's track should be specified via
8831:   // For built-in counters (e.g. thread time). Custom user-specified counters
8850:   // COUNTER_THREAD_TIME_NS timestamps in microseconds instead.
8855:   // thread time). Counter values in subsequent packets on the current packet
8896:   // Similarly, to associate a COUNTER_THREAD_TIME_NS counter track with a
8897:   // thread, specify the uuid for that thread's thread track here.
8901:   // process/thread name (process/thread tracks), the first event's name (async
8916:   // Associate the track with a thread, indicating that the track's events
8917:   // describe synchronous code execution on the thread. There should only be one
8918:   // such track per thread (trace processor uses this fact to detect tid reuse).
8920:   // Trace processor will merge events on a thread track with slice-type events
8921:   // from other sources (e.g. ftrace) for the same thread into a single timeline
7168:     // Delta timestamp value since the last TrackEvent or ThreadDescriptor. To
7170:     // preceding TrackEvents since the last ThreadDescriptor and add the sum to
7171:     // the |reference_timestamp| in ThreadDescriptor. This value should always
7186:     // Delta timestamp value since the last TrackEvent or ThreadDescriptor. To
7188:     // preceding TrackEvents since the last ThreadDescriptor and add the sum to
7189:     // the |reference_timestamp| in ThreadDescriptor. This value should always
7265:     // pid+tid from ThreadDescriptor is used.
8069:   // TODO(eseckler): ThreadDescriptor-based timestamps are deprecated. Replace
8292: // Metadata about the processes and threads in the trace.
8295: // trace writers should prefer to fill ThreadDescriptor and ProcessDescriptor
8323:     // No longer used as of Apr 2018, when the dedicated |threads| field was
8331:   // List of processes and threads in the client. These lists are incremental
8332:   // and not exhaustive. A process and its threads might show up separately in
8335:   // #0 { processes: [{pid: 10, ...}], threads: [{pid: 11, tgid: 10}] }
8336:   // #1 { threads: [{pid: 12, tgid: 10}] }
8337:   // #2 { processes: [{pid: 20, ...}], threads: [{pid: 13, tgid: 10}] }
8619:     // Tracing related threads:
9147:     // Process/ThreadDescriptors. This flag only affects the current packet
chromium.googlesource.com/chromium/deps/psyco_win32:psyco/profiler.py: [ master, ]
20:     import dummy_thread as thread
365: def psyco_start_new_thread(callable, args, kw=None):
371: original_start_new_thread = thread.start_new_thread
358: def psyco_thread_stub(callable, args, kw):
18:     import thread
32: # a lock for a thread-safe go()
33: go_lock = thread.allocate_lock()
260:         self.lock = thread.allocate_lock()
343: # and thread.start_new_thread().
366:     "This is the Psyco-aware version of thread.start_new_thread()."
367:     return original_start_new_thread(psyco_thread_stub, (callable, args, kw))
374: thread.start_new_thread = psyco_start_new_thread
375: # hack to patch threading._start_new_thread if the module is
378:     hasattr(sys.modules['threading'], '_start_new_thread')):
379:     sys.modules['threading']._start_new_thread = psyco_start_new_thread
204:             alarm.stop(1)   # wait for parallel threads to stop
377: if ('threading' in sys.modules and
android.googlesource.com/platform/external/rust/crates/parking_lot_core:src/parking_lot.rs: [ master, ]
1257:         Thread(*const ThreadData),
1132:         thread_id: usize,
1138:         pub fn thread_id(&self) -> usize {
1159:         thread_id: usize,
127: struct ThreadData {
151: impl ThreadData {
186: impl Drop for ThreadData {
1131:     pub struct DeadlockedThread {
1136:     impl DeadlockedThread {
173: fn with_thread_data<T>(f: impl FnOnce(&ThreadData) -> T) -> T {
19: static NUM_THREADS: AtomicUsize = AtomicUsize::new(0);
474:     pub unparked_threads: usize,
477:     pub requeued_threads: usize,
481:     pub have_more_threads: bool,
1523:         num_threads: usize,
7: use crate::thread_parker::{ThreadParker, ThreadParkerT, UnparkHandleT};
29: // Even with 3x more buckets than threads, the memory overhead per thread is
30: // still only a few hundred bytes per thread.
130:     // Key that this thread is sleeping on. This may change if the thread is
137:     // UnparkToken passed to this thread when it is unparked
140:     // ParkToken value set by the thread when it was parked
143:     // Is the thread parked with a timeout?
171: // Invokes the given closure with a reference to the current thread `ThreadData`.
175:     // to construct. Try to use a thread-local version if possible. Otherwise just
177:     let mut thread_data_storage = None;
178:     thread_local!(static THREAD_DATA: ThreadData = ThreadData::new());
179:     let thread_data_ptr = THREAD_DATA
181:         .unwrap_or_else(|_| thread_data_storage.get_or_insert_with(ThreadData::new));
183:     f(unsafe { &*thread_data_ptr })
215:     // If this fails then it means some other thread created the hash table first.
239: // created, which only happens once per thread.
255:         // Now check if our table is still the latest one. Another thread could
281:     // any other thread trying to grow the hash table is blocked on the bucket
344:         // If no other thread has rehashed the table before we grabbed the lock
409:         // If no other thread has rehashed the table before we grabbed the lock
448:     /// We were unparked by another thread with the given token.
459:     /// Returns true if we were unparked by another thread.
480:     /// true if a thread was unparked.
498:     /// Unpark one thread and requeue the rest onto the target queue.
504:     /// Unpark one thread and leave the rest parked. No requeuing is done.
507:     /// Requeue one thread and leave the rest parked on the original queue.
511: /// Operation that `unpark_filter` should perform for each thread.
514:     /// Unpark the thread and continue scanning the list of parked threads.
517:     /// Don't unpark the thread and continue scanning the list of parked threads.
520:     /// Don't unpark the thread and stop scanning the list of parked threads.
524: /// A value which is passed from an unparker to a parked thread.
528: /// A value associated with a parked thread which can be used by `unpark_filter`.
538: /// Parks the current thread in the queue associated with the given key.
542: /// current thread is appended to the queue and the queue is unlocked.
545: /// the thread is put to sleep. The thread will then sleep until it is unparked
552: /// whether it was the last thread in the queue.
575:     // Grab our thread data, this also ensures that the hash table exists
576:     with_thread_data(|thread_data| {
587:         // Append our thread data to the queue and unlock the bucket
588:         thread_data.parked_with_timeout.set(timeout.is_some());
589:         thread_data.next_in_queue.set(ptr::null());
590:         thread_data.key.store(key, Ordering::Relaxed);
591:         thread_data.park_token.set(park_token);
592:         thread_data.parker.prepare_park();
594:             (*bucket.queue_tail.get()).next_in_queue.set(thread_data);
596:             bucket.queue_head.set(thread_data);
598:         bucket.queue_tail.set(thread_data);
605:         // Park our thread and determine whether we were woken up by an unpark
609:             Some(timeout) => thread_data.parker.park_until(timeout),
611:                 thread_data.parker.park();
613:                 deadlock::on_unpark(thread_data);
620:             return ParkResult::Unparked(thread_data.unpark_token.get());
625:         let (key, bucket) = lock_bucket_checked(&thread_data.key);
629:         if !thread_data.parker.timed_out() {
632:             return ParkResult::Unparked(thread_data.unpark_token.get());
635:         // We timed out, so we now need to remove our thread from the queue
639:         let mut was_last_thread = true;
641:             if current == thread_data {
652:                             was_last_thread = false;
660:                 // last thread on the queue.
661:                 timed_out(key, was_last_thread);
665:                     was_last_thread = false;
673:         // There should be no way for our thread to have been removed from the queue
684: /// Unparks one thread from the queue associated with the given key.
687: /// target thread is woken up. The `UnparkResult` argument to the function
688: /// indicates whether a thread was found in the queue and whether this was the
689: /// last thread in the queue. This value is also returned by `unpark_one`.
692: /// passed to the thread that is unparked. If no thread is unparked then the
711:     // Find a thread with a matching key and remove it from the queue
718:             // Remove the thread from the queue
736:             // Invoke the callback before waking up the thread
741:             // Set the token for the target thread
745:             // the thread from exiting and freeing its ThreadData if its wait
748:             // up the parked thread.
792:             // Remove the thread from the queue
799:             // Set the token for the target thread
839: /// indicating whether a thread was unparked and whether there are threads still
844: /// passed to the thread that is unparked. If no thread is unparked then the
880:     let mut wakeup_thread = None;
883:             // Remove the thread from the queue
890:             // Prepare the first thread for wakeup and requeue the rest.
892:                 && wakeup_thread.is_none()
894:                 wakeup_thread = Some(current);
940:     // Invoke the callback before waking up the thread
947:     if let Some(wakeup_thread) = wakeup_thread {
948:         (*wakeup_thread).unpark_token.set(token);
949:         let handle = (*wakeup_thread).parker.unpark_lock();
963: /// `ParkToken` associated with each thread.
965: /// The `filter` function is called for each thread in the queue or until
967: /// associated with a particular thread, which is unparked if `FilterOp::Unpark`
976: /// passed to all threads that are unparked. If no thread is unparked then the
1004:             // Call the filter function with the thread's ParkToken
1008:                     // Remove the thread from the queue
1014:                     // Add the thread to our list of threads to unpark
1090:     /// Panics if the resource was already released or wasn't acquired in this thread.
1118:     use super::{get_hashtable, lock_bucket, with_thread_data, ThreadData, NUM_THREADS};
1119:     use crate::thread_parker::{ThreadParkerT, UnparkHandleT};
1128:     use thread_id;
1130:     /// Representation of a deadlocked thread
1137:         /// The system thread id
1139:             self.thread_id
1142:         /// The thread backtrace
1158:         // System thread id
1168:                 thread_id: thread_id::get(),
1178:                     thread_id: td.deadlock_data.thread_id,
1188:             unreachable!("unparked deadlocked thread!");
1193:         with_thread_data(|thread_data| {
1194:             (*thread_data.deadlock_data.resources.get()).push(key);
1199:         with_thread_data(|thread_data| {
1200:             let resources = &mut (*thread_data.deadlock_data.resources.get());
1229:         let thread_count = NUM_THREADS.load(Ordering::Relaxed);
1230:         let mut graph = DiGraphMap::<usize, ()>::with_capacity(thread_count * 2, thread_count * 2);
1264:     // Returns all detected thread wait cycles.
1277:             // Now check if our table is still the latest one. Another thread could
1293:         let thread_count = NUM_THREADS.load(Ordering::Relaxed);