Monday, October 20, 2014

Unix Prog: thread identification

1. Thread Concepts

With multiple threads, we can design our program to do more than one thing at a time within a single process.
1) We can assign each thread to handle each event type within the process.
2) Threads automatically have the access to the same memory address space and file descriptors
3) Problems can be partitioned and overall throughput can be improved
4) Interactive program can improve the response time by using multiple threads separate calculation and user IO

The benefits of multi-threading  can be realized even if with uni-processor.

Thread contains context information within the process, including:
1) thread id
2) a set of register values
3) a stack
4) scheduling priority and policy
5) signal mask
6) errno variable
7) thread specific data

2. Thread Identification
Unix use type "pthread_t" to identify the thread, and UNIX implementations are allowed to implement it with struct or integers. So there is no portable way to print out the pthread_t type.

Definition:
In current system, it is unsigned long int.
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h  
 ......  
 /* Thread identifiers. The structure of the attribute type is not  
   exposed on purpose. */  
 typedef unsigned long int pthread_t;  
 ......  

And UNIX provide common interface to compare two pthread ids:
If returning 0, means not equal; if returning non-0, means equal
 ubuntu@ip-172-31-23-227:~$ less /usr/include/pthread.h  
 ......  
 /* Compare two thread identifiers. */  
 extern int pthread_equal (pthread_t __thread1, pthread_t __thread2)  
  __THROW __attribute__ ((__const__));  
 ......  

And the way to get current pthread id:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/pthread.h  
 ......  
 /* Obtain the identifier of the current thread. */  
 extern pthread_t pthread_self (void) __THROW __attribute__ ((__const__));  
 ......  

3. Example:
thread.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<pthread.h>  
   
 int main(int argc, char* argv[])  
 {  
  pthread_t tid = 0;  
  printf("Current thread id: %ld\n", pthread_self());  
  if(pthread_equal(tid, pthread_self()) != 0) {  
   printf("Current thread id is equal to 0\n");  
  }  
  else {  
   printf("Current thread id is not equal to 0\n");  
  }  
  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./thread.out  
 Current thread id: 0  
 Current thread id is equal to 0  

No comments:

Post a Comment