pthread_create 函数引发的几点思考

pthread_create 函数引发的几点思考

1、  syscall(SYS_gettid) 与pthread_self的区别:

    一个是系统调用(LWP),一个是POSIX定义的内容(pthread),两者并不一样,其中gettid常在core文件中看到。两者的值并不一样

2、  堆与栈的区别

    堆是要自己申请并释放的,系统会回收(对于C++而言,对应于new和delete);但对于栈来说,系统回收的方法只是把栈顶指针往下移(让出存储空间),并没有实际释放对象,因此仍然可以访问到对象的值(只有不被覆盖,适用于大部分平台)。

3、  进程退出时,如何让出控制权

    当主进程退出时,由主进程创建的线程也将退出。通过调用pthread_exit()可以让进程让出控制权,进而使子线程继续运行

程序代码:

#include<unistd.h>
#include<sys/syscall.h>
#include<pthread.h>
#include<iostream>
usingnamespace std;
classTestClass{
public:
       TestClass() {cout << __FUNCTION__<< " is called!" << endl;}
       ~TestClass() {cout << __FUNCTION__<< " is called!" << endl;}
       string str;
};
void*handler(void * arg)
{
       cout << static_cast<TestClass*>(arg)->str << endl;
       //sleep for a while
       sleep(2);
       cout << "Process id = "<< getpid() <<  ",thread id = " << pthread_self() << ", gettid = "<< syscall(SYS_gettid) << endl;
       cout << static_cast<TestClass*>(arg)->str << endl;
      
}
 
intmain(int argc, char **argv)
{
    pthread_t pid;
    {
              TestClassparam;
              param.str= "hello";   
              pthread_create(&pid,NULL, handler, ¶m);
              sleep(1);
    }
    //继续生成一个栈对象,有的平台上会替换原来的栈对象
    TestClass param;
    param.str = "hello, world!";
    cout << "Enterpthread_join" << endl;
    pthread_join(pid, NULL);
    pthread_exit(0);   // 用这个函数,便可以去掉pthread_join函数,会等待子线程的退出,然后退出主线程
    return 0;
}

在centOS平台上运行该程序,结果如下:


在ubuntu 平台上运行,则上面空行会是 hello,world!   ^_^不要诧异

    如果传递过去的是堆对象,当对象析构后将无法得到正确的结果。一般做法在线程里面保存传入的参数。

原文地址:https://www.cnblogs.com/OpenLinux/p/5020709.html