Is it possible to read another thread's program counter? - c

Is is possible (in a C or C++ program, running under Linux on a 64-bit-Intel architecture) for thread A to read the value of thread B's program counter register, without requiring any special instrumentation of to thread B's code?
(I realize that's an odd thing to want to do; the desire only comes up because I'm curious if thread A could use that to detect if thread B had become stuck in a failed system call, as described here)

On Linux, field 30 of /proc/self/task/%d/stat, where %d needs to be filled in with the kernel tid of the thread in question, contains the last-observed instruction pointer value for the thread. See http://man7.org/linux/man-pages/man5/proc.5.html and note that it's documented under /proc/[pid]/stat but the version in the task directory under the current process is the one you want for targeting a thread.
The hard part may be getting the kernel tid for the thread. The easiest way to do this is to call syscall(SYS_gettid) from the thread and have it store its kernel tid somewhere.

Related

Pthread Join in C?

I'm writing code to save text to a binary file, which includes a function to auto-save text to the binary file, as well as a function to print from the binary file, and I need to incorporate pthread locks and join. We were given
pthread_mutext_t mutex;
pthread_t autosavethread;
as global variables, although the instructor didn't talk about what pthread or mutex actually do, so I'm confused about that.
Also, I understand that I need to use locks whenever shared variables are changed or read (in my case it would be the binary file). But at the end of the file I am supposed to use pthread_join, and I don't know what it does or what arguments are supposed to be used in it. I'm guessing mutex and autosavethread are supposed to be closed, or something along the lines of that, but I don't know how to write it. Can anyone help better my understanding?
There are two types of pthread - joinable thread & detached thread.
If you want to let a thread just take a task and go away once the task is done, you need the detached thread;
If you want to have the communication with the created thread when that thread is done with the assigned job, you have to use joinable thread. Basically it's needed when the parent & its created thread need to communicate after the thread is done.
It's very to google what exactly you need to call the pthread APIs and what can be communicated.
But one thing i want to mention here is, for the joinable thread, you have to explicitly call the pthread_join against the created thread. Otherwise, there will be serious memory leaks. When the joinable thread completes its task, the thread seems to exit (On linux, you can check the /proc/PID/task/ folder and once the thread completes, the entry under it will go away), but the resource allocated for this joinable thread, i.e. stack, is still there in the process memory space. As more and more joinable threads created and completing their tasks, the stacks for each thread are just left in process space, unless you explicitly call the pthread_join. Hope that helps, even a bit

Linux thread id recycle strategy

What's the recycle strategy of Linux thread ID ?
Linux process ID will not be reused immediately unless new PID get the max limitation and being rewinded.
When I use pthread_self() to get thread id, I got TIDs like 1028, 1034. I guess it is the inner "serial number" of threads in a process. So I guess it would be more appropriate to use a thread id recycle strategy like PID recycle strategy.
But I am not quite sure whether it is true as to Linux pthread implementation.
A threaded linux process has
an OS pid shared by all threads within the process - use getpid
each thread within the process has its own OS thread id - use gettid
a pthreads thread id used internally by pthreads to identify threads when making various pthread related calls - use pthread_self and similar.
It can't be determine from your question if you trying to implement a "recycle strategy" or why you think you need to do so.
Edit
As an idle curiosity you can look through the linux pthread code but technically you have no reason to care. The POSIX spec basically just says the thread id is guaranteed to be unique within a process and is free to be reused after a thread dies.
Although implementations may have thread IDs that are unique in a system, applications should only assume that thread IDs are usable and unique within a single process. The effect of calling any of the functions defined in this volume of IEEE Std 1003.1-2001 and passing as an argument the thread ID of a thread from another process is unspecified. A conforming implementation is free to reuse a thread ID after the thread terminates if it was created with the detachstate attribute set to PTHREAD_CREATE_DETACHED or if pthread_detach() or pthread_join() has been called for that thread.
In linux threads are implemented as processes (with shared memory and other stuff)
so the kernel thread ids (the ones you get through gettid()) are really process ids.
This is also indicated by the fact that the id of first thread of a process and that process' id are one and the same.
Now i don't know exactly what is the pid-allocation algorithm employed by the linux kernel, but i believe it makes some effort to avoid rapid pid reuse (i think i have read about that somewhere but cant remember).
Note that those are the kernel thread ids (returned by the syscall gettid()), which is different thing from the "pthread_t" (returned by the library function pthread_self()).
While both can be used to uniquely identify threads, the former is linux-specific, so if your code needs to be portable you better avoid it (or use #ifdef-s).

NetServerEnum block when thread is terminated externaly

(Working in Win32 api , in C environment with VS2010)
I have a two thread app. The first thread forks the second and waits for a given interval - 'TIMEOUT', and then calls TerminateThread() on it.
Meanwhile, second thread calls NetServerEnum().
It appears that when timeout is reached , whether NetServerEnum returned successfully or not, the first thread get deadlocked.
I've already noticed that NetServerEnum creates worker threads of it's own.
I ultimately end up with one of those threads in deadlock, typically on ntdll.dll!RtlInitializeExceptionChain, unable to exit my process gracefully.
As this to too long for a comment:
Verbatim from MSDN, allow me to use te answer form (emphasis by me):
TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:
If the target thread owns a critical section, the critical section will not be released.
If the target thread is allocating memory from the heap, the heap lock will not be released.
*If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
From reading this it is easy to understanf why it is a bad idea to cancel (terminate) a thread stucking in a system call.
A possible alternative approach to the OP's design might be to spawn off a thread calling NetServerEnum() and simply let it run until the system call returned.
In the mean while the main thread could do other things like for example informing the user that scanning the net takes longer as expected.

Which thread holds the lock

I am working on C and I have a core dump of a multithreaded (two threads) process that I am debugging.
I see in gdb that the mutex_lock is acquired by both the threads under a rare situation. Is there a way I could check the thread that possess the lock in gdb?
I am running a flavor of linux..
Also, I am not allowed to post the code since it's proprietary.
On every line that gets and releases the lock in question (of course change the printf text), do the following:
break file:line
commands
printf "acquiring lock"
info threads
cont
end

C linux pthread thread priority

My program has one background thread that fills and swaps the back buffer of a double buffer implementation.
The main thread uses the front buffer to send out data. The problem is the main thread gets more processing time on average when I run the program. I want the opposite behavior since filling the back buffer is a more time consuming process then processing and sending out data to the client.
How can I achieve this with C POSIX pthreads on Linux?
In my experience, if, in the absence of prioritisation your main thread is getting more CPU then this means one of two things:
it actually needs the extra time, contrary to your expectation, or
the background thread is being starved, perhaps due to lock contention
Changing the priorities will not fix either of those.
have a look at pthread_setschedparam() --> http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_setschedparam.3.html
pthread_setschedparam(pthread_t thread, int policy,
const struct sched_param *param);
You can set the priority in the sched_priority field of the sched_param.
Use pthread_setschedprio(pthread_t thread, int priority). But as in other cases (setschedparam or when using pthread_attr_t) your process should be started under root, if you want to change priorities (like nice utility).
You should have a look at the pthread_attr_t struct. It's passed as a parameter to the pthread_create function. It's used to change the thread attributes and can help you to solve your problem.
If you can't solve it you will have to use a mutex to prevent your main thread to access your buffer before your other thread swaps it.

Resources