How to Know Which Thread Is Executing A Specific Print Statement

Hi,

I have created two threads and I am also using conditional variables. I want to know which thread is executing a specific print statement?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

// C program to implement cond(), signal() 
// and wait() functions 
#include <pthread.h> 
#include <stdio.h> 
#include <unistd.h> 
  
// Declaration of thread condition variable 
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; 
  
// declaring mutex 
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 
  
int done = 1; 
  
// Thread function 
void* foo() 
{ 
  
    // acquire a lock 
    pthread_mutex_lock(&lock); 
    if (done == 1) { 
  
        // let's wait on conition varible cond1 
        done = 2; 
        printf("Waiting on condition variable cond1\n"); 
        pthread_cond_wait(&cond1, &lock); 
    } 
    else { 
  
        // Let's signal condition variable cond1 
        printf("Signaling condition variable cond1\n"); 
        pthread_cond_signal(&cond1); 
    } 
  
    // release lock 
    pthread_mutex_unlock(&lock); 
    /* How can I know which thread is printing the following line */
    printf("Returning thread\n"); 
  
    return NULL; 
} 
  
// Driver code 
int main() 
{ 
    pthread_t tid1, tid2;
     // Create thread 1 
    pthread_create(&tid1, NULL, foo, NULL); 
  
    // sleep for 1 sec so that thread 1 
    // would get a chance to run first 
    sleep(1); 
  
    // Create thread 2 
    pthread_create(&tid2, NULL, foo, NULL); 
  
    // wait for the completion of thread 2 
    pthread_join(tid2, NULL); 
  
    return 0; 
}  


In the foo() function, I want to know which thread is executing the following line:

/* How can I know which thread is printing the following line */
printf("Returning thread\n");

How thread id can help me to identify the thread which would print the above line first?
I am getting following output:

Waiting on condition variable cond1
Signaling condition variable cond1
Returning thread
Returning thread


Some body please guide.

Zulfi.

NAME
pthread_self - obtain ID of the calling thread

SYNOPSIS
#include <pthread.h>

pthread_t pthread_self(void);

Put that in your printf statements.
Hi
Thanks salem. Your solution worked. I have to use %lu format.

printf("Returning thread %lu\n",pthread_self());

Following is my output for my above code:
Waiting on condition variable cond1
Signaling condition variable cond1
Returning thread 139758132209408
Returning thread 139758140602112


Zulfi.
Registered users can post here. Sign in or register to post.