pthread_create thinking

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <pthread.h>
  5 #include <unistd.h>
  6 int message=10;
  7 void printids(const char *str) {
    
    
  8     pid_t pid = getpid();
  9     pthread_t tid = pthread_self();
 10     printf("%s pid: %u, tid: %u, tid in 0x presentation: 0x%x.\n",str, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
 11     printf("%s, message is %d\n",str,message);
 12 }
 13 
 14 void *func(void *arg) {
    
    
 15     pthread_detach(pthread_self());
 16     sleep(2);  // 等待主线程先退出
 17     printids("descendant thread");
 18     printf("fun  is  %d   address is %p\n",*((int*)arg),arg);
 19     return;
 20 }
 21 
 22 int main(void) {
    
    
 23     int message_2=20;
 24     pthread_t myid;
 25     pthread_create(&myid, NULL, func,&message_2);
 26     printf("message_2  address is %p\n",&message_2);
 27 
 28     printids("main thread");
 29     pthread_exit(NULL);
 30 
 31     return 0;  //进程退出,系统清除所有资源
 32 }

print

message_2  address is 0x7ffdda6a2e0c
main thread pid: 12009, tid: 4195251968, tid in 0x presentation: 0xfa0e7700.
main thread, message is 10
descendant thread pid: 12009, tid: 4186924800, tid in 0x presentation: 0xf98f6700.
descendant thread, message is 10
fun  is  20   address is 0x7ffdda6a2e0c

Analysis:
1. As a local variable in the main function, message_2 is not destroyed after the main thread ends.
The arg address in thread myid is the same as the message_2 address in the main thread.
2 The global variable message can still be used by the thread myid after the main thread ends.
3 Through the entire execution process, it can be seen that the unit of sleep is the thread, and the end of the thread myid will not affect the main thread.
4 Multi-threaded data space is shared, so local variables in the main function should not be destroyed because a thread ends.

Guess you like

Origin blog.csdn.net/aningxiaoxixi/article/details/113462740