pthread_create 思索

  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 }

打印

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

分析:
1 message_2 做为main 函数里面的局部变量,在主线程结束后,并没有被销毁。
线程myid 里面的 arg 地址跟主线程中的 message_2 地址是一样的。
2 全局变量 message 在主线程结束后,依旧可以被线程myid 使用。
3 通过整个执行过程,可知 sleep 休眠的单位是线程,线程myid结束,并不会影响主线程。
4 多线程数据空间是共享的,那么不应该因为某个线程结束,而销毁main 函数中的局部变量。

猜你喜欢

转载自blog.csdn.net/aningxiaoxixi/article/details/113462740