OS is Linux, working with pthreads
I have two worker threads that run forever, until a stop variable takes value true, and the threads terminate gracefully. Instead of doing busy waiting both threads call pthread_cond_wait until a signal notifies for a new task. The system works well.
It is requested to create an "info" thread that will print some debugging information. The info thread will try to read and print information every 30 seconds.Part of this info, I would like to be the STATE of each worker thread. Is it possible to find if a thread is blocked in "pthread_cond_wait"? If the thread waits is pthread_cond_wait then STATE==waiting else the STATE==running.
while ( (sharedvaluffer == 0) && (doneflag == 0) ) {
pthread_cond_wait (&taks_added, &buffer);
}
Of course we can do that we more code. We can add to the above snippet a global variable that marks that thread as locked. The code can be done
while ( (sharedvaluffer == 0) && (doneflag == 0) ) {
lock;
i_am_waiting = truel
unlock
pthread_cond_wait (&taks_added, &buffer);
}
The question is, if there is an easier more scalable way. The stack of a waiting thread is
Thread 6 (Thread 0x40800940 (LWP 20732)):
#0 0x00002ba4567a9326 in pthread_cond_wait@@GLIBC_2.3.2 ()
#1 0x00000000007ce2ed in worker(void*) ()
#2 0x00002ba4567a5193 in start_thread () from /lib64/libpthread.so.0
#3 0x00002ba458a82f0d in clone () from /lib64/libc.so.6
The top command can show a real-time view of individual threads. To enable thread views in the top output, invoke top with "-H" option. This will list all Linux threads. You can also toggle on or off thread view mode while top is running, by pressing 'H' key.
If you have launched your thread with specified pthread_attr , and this pthread_attr is still around, you can reliably check the joinable state by calling pthread_attr_getdetachstate .
Yes. The typical problem, however, is that the work/threads are not constrained. Using the approach you have outlined, it's easy to spawn many threads and have an illogically high number of threads for the work which must be executed on a limited number of cores.
pthread_create() returns zero when the call completes successfully. Any other return value indicates that an error occurred. When any of the following conditions are detected, pthread_create() fails and returns the corresponding value.
You could register a shared structure s in the mutex with pthread_mutexattr_getpshared, where each thread registers its state (running, not running) with the aid of pthread_self()
.
Before checking the condition variable, you can set s[pthread_self()]->state = WAITING
, and after the check you can set s[pthread_self()]->state = WORKING
.
Be sure to design the structure such as no race condition will occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With