0

Using pthreads for C, is there a way to access the program counter/instruction pointer for specific threads?

Example:

void *thread_main(void *arg) {
  long thread = (long)arg;

  lock (thread);
  ***print (thread.pc);*** 
  critical_section (thread);
  ***print (thread.pc);***  
  unlock (thread);

  return NULL;
}
  • Are you looking for a cross-platform solution, or do you just need this to work on a specific platform (e.g. Windows, etc). – i_am_jorf Jan 26 '17 at 19:27
  • 2
    C has no concept of a "program counter". You can use the `__FILE__`, `__func__` and `__LINE__` macros to identify which part of the code is currently executing. – EOF Jan 26 '17 at 19:32
  • @i_am_jorf I have a MacOS and a Debian machine. So either would be acceptable :) – BabblingMonkey Jan 26 '17 at 19:55
  • Would writing a function which picks up return address from stack solve your problem? – vguberinic Jan 26 '17 at 19:58
  • 1
    You can access registers using [these](http://stackoverflow.com/q/3022046/74815) solutions, but you'll need to do it on the thread you care about, as far as I know. – i_am_jorf Jan 26 '17 at 21:09
  • I don't understand the downvote here. This is a legitimate programming question that undoubtedly has a solution. – i_am_jorf Jan 26 '17 at 23:00
  • in general, the parameter to a thread should be a pointer, not a value, so this line: `long thread = (long)arg;` should be: `long thread = (long*)arg;` – user3629249 Jan 27 '17 at 00:05
  • when asking runtime questions, such as this one, post the actual input(s) post the actual outputs, post a short (cleanly compiles) code that still exhibits the problem. BTW: just what is your problem? – user3629249 Jan 27 '17 at 00:06
  • @user3629249 I create the threads as: pthread_create(&pid[i], NULL, &thread_body, (void*)((long)i)); – BabblingMonkey Feb 03 '17 at 14:39
  • OOps, I made an error, the line: `long thread = (long)arg;` should be: `long thread = *(long*)arg`. because should be passing a pointer, not the actual value. Per your comment, should create the thread with: `pthread_creat( *pid[i], NULL, &thread_body, &i );` assuming the `i` is actually a `long` variable/ Among other reasons, because a `long` might not be the same size as a pointer. – user3629249 Feb 03 '17 at 18:01

1 Answers1

0

Check out backtrace(); it is supported on both your platforms.

    #include <execinfo.h>
    ....
        void * pc;
        backtrace(&pc, 1);
    ....

See man 3 backtrace for details. Beware that all threads running the same thread_main will report the same pc.

user58697
  • 7,808
  • 1
  • 14
  • 28