MCPcopy Create free account
hub / github.com/RT-Thread/rt-thread / search

Function search

examples/libc/ex3.c:77–162  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

75/* This is the search routine that is executed in each thread */
76
77void *search(void *arg)
78{
79 int num = (int) arg;
80 int i, j, ntries;
81 pthread_t tid;
82
83 /* get the calling thread ID */
84 tid = pthread_self();
85
86 /* use the thread ID to set the seed for the random number generator */
87 /* Since srand and rand are not thread-safe, serialize with lock */
88
89 /* Try to lock the mutex lock --
90 if locked, check to see if the thread has been cancelled
91 if not locked then continue */
92 while (pthread_mutex_trylock(&lock) == EBUSY)
93 pthread_testcancel();
94
95 srand((int)tid);
96 i = rand() & 0xFFFFFF;
97 pthread_mutex_unlock(&lock);
98 ntries = 0;
99
100 /* Set the cancellation parameters --
101 - Enable thread cancellation
102 - Defer the action of the cancellation */
103
104 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
105 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
106
107 while (started < NUM_THREADS)
108 sched_yield ();
109
110 /* Push the cleanup routine (print_it) onto the thread
111 cleanup stack. This routine will be called when the
112 thread is cancelled. Also note that the pthread_cleanup_push
113 call must have a matching pthread_cleanup_pop call. The
114 push and pop calls MUST be at the same lexical level
115 within the code */
116
117 /* Pass address of `ntries' since the current value of `ntries' is not
118 the one we want to use in the cleanup function */
119
120 pthread_cleanup_push(print_it, (void *)&ntries);
121
122 /* Loop forever */
123 while (1) {
124 i = (i + 1) & 0xFFFFFF;
125 ntries++;
126
127 /* Does the random number match the target number? */
128 if (num == i) {
129 /* Try to lock the mutex lock --
130 if locked, check to see if the thread has been cancelled
131 if not locked then continue */
132 while (pthread_mutex_trylock(&lock) == EBUSY)
133 pthread_testcancel();
134

Callers

nothing calls this directly

Calls 11

pthread_selfFunction · 0.85
pthread_mutex_trylockFunction · 0.85
pthread_testcancelFunction · 0.85
pthread_mutex_unlockFunction · 0.85
pthread_setcancelstateFunction · 0.85
pthread_setcanceltypeFunction · 0.85
sched_yieldFunction · 0.85
pthread_cleanup_pushFunction · 0.85
pthread_cancelFunction · 0.85
pthread_cleanup_popFunction · 0.85
printfFunction · 0.50

Tested by

no test coverage detected