函数定义,已经相应的头文件
#include <pthread.h>
int pthread_create(pthread_t *thread, constpthread_attr_t *attr,
void*(*start_routine) (void *), void *arg);
创建线程
注意编译的时候link上-pthread.
/**
* 功能:创建一个线程
* 时间:2015年12月26日17:00:36
* 作者:cutter_point
*/
#include "../util/apue.h"
#include "../util/error.c"
#include <pthread.h>
pthread_t ntid; //the thread id
//打印进程ID和线程id
void printids(const char *s)
{
pid_t pid; //进程id
pthread_t tid;
//get process id
pid = getpid();
//get thread id
sleep(1);
tid = pthread_self();
//out put
printf("%s\t pid:%lu\ttid:%lu\t(0x)%lx\n", s, (unsigned long)pid,
(unsigned long)tid, (unsigned long)tid);
}
void test();
//the thread begin
void * thr_fn(void *arg)
{
printids("new thread:");
test();
return ((void*)0);
}
//my test if thread begin include this?
void test()
{
printf("just test for thread where it begin!\n");
}
int main(int argc, char *argv[])
{
int err; //if create thread fail return this number
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if(err != 0)
err_exit(err, "can`t create new thread");
printids("main thread:");
sleep(1); //this is because if main stop the thread have no chance to begin
exit(0);
}
我们在Linux中编译
gcc -pthread -gthreadid.cpp -o threadid.out
我们的进程id是一样的,说明这两段程序执行的时候是在同一个进程中的,但是后面的线程id是不一样的,原因是:主线程吧新线程的id存放在ntid中,当主线程获取相应的线程id的时候,新线程在主线程调用pthread_create返回直线就执行了,那么新线程得到的是还没有初始化的id