《POSIX多线程程序设计》笔记(3) 线程的创建与使用

#include <pthread.h>
#include "errors.h"

void *thread_routine(void *arg)
{
    return arg;
}

int main(int argc, char *argv[])
{
    pthread_t thread_id;
    void *thread_result;
    int status;

    /*线程的创建(pthread_create)和被调度执行(thread_routine),
     *两者之间不存在同步关系;
      即新线程可能在当前线程从pthread_create返回前就运行了,
      甚至,在当前线程从pthread_create返回前就已经执行完成了. */
    status = pthread_create(&thread_id, NULL, thread_routine, NULL);
    if (status != 0)
    {   
        err_abort(status, "Create thread");
    }   
    status = pthread_join(thread_id, &thread_result);
    if (status != 0)
    {   
        err_abort(status, "Join thread");
    }   

    /*在初始线程中直接return, 系统将直接调用exit()进程退出,进而导致其他普通线程被强制退出;
     *在初始线程中调用pthread_exit(),将避免进程过早的退出.*/
    if (thread_result == NULL)
        return 0;
    else
        return 1;
}

/* 初始线程(主线程)和普通线程的区别:
 *     1.调用参数不同, 主线程是argc,argv,普通线程是void* ;
 *     2.初始线程主动调用pthread_exit(), 可以防止进程过早结束;
 *     3.多数系统中,初始线程运行在进程堆栈中,其堆栈长度可以增长到足够长
 *       而普通线程的堆栈通常是受限的,如果线程堆栈溢出,则将引发段错误或总线错误. */

/*如果有其他线程在等待连接进入终止态的线程, 则这些线程将被唤醒(有且只有一个连接成功),
 *并从pthread_join返回相应的值. 一旦获取返回值,终止态的线程就被分离并“可能”在pthread_join返回前被回收,
 *这意味着, 线程返回值不应该是与终止线程堆栈相关的地址(可能已经是非法内存了.) */ 
原文地址:https://www.cnblogs.com/orejia/p/12562793.html