[unix]线程创建

#include "apue.h"
#include 

pthread_t ntid;

void printids(const char *s)
{
    pid_t pid;
    pthread_t tid;
    pid = getpid();
    /*这里用pthread_self函数获取当前线程id,而不是用pthread_create执行时候保存在全局变量ntid
        是为了防止 pthread_create在返回之前,新线程已经运行完了,ntid得到就不是正确当前线程id
        */
    tid = pthread_self();
    printf("%s pid %lu tid %lu (0x%lx)\n",s,(unsigned long)pid, (unsigned long)tid,(unsigned long)tid);
}

void *thr_fn(void *arg)
{
    printids("new thread: ");
    return((void *)0);
}

int  main(int argc,char **argv)
{
    int err;
    err = pthread_create(&ntid, NULL, thr_fn,NULL);
    if(err != 0)
        err_exit(err,"can't create thread");
    printids("main thread:");
    sleep(1);  /*主线程需要休眠,因为它会退出,如果它先退出,导致新线程没机会执行*/
    exit(0);
}

学无止境不耻下问:https://includestdio.com

你可能感兴趣的:(编程语言,unix,系统)