#include<pthread.h> #include<stdio.h> pthread_t ntid; void printids(const char *s) { pid_t pid; pthread_t tid; pid=getpid(); tid=pthread_self(); printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid, (unsigned int)tid,(unsigned int)tid); } void *thr_fn(void *arg) { printids("new thread: "); return ((void *)0); } int main(void) { int err; err = pthread_create(&ntid,NULL,thr_fn,NULL); printf("ntid= %d",ntid); if(err!=0) printf("can't create thread : %s\n"); printids("main thread:"); sleep(1); exit(0); }
编译时候需添加-pthread选项,或者-lpthread选项,否则出现undefined reference to 'pthread_create’
因为默认情况下pthread_create不是linux系统默认连接的库
关于-pthread与-lpthread选项区别可以参见此文
http://chaoslawful.iteye.com/blog/568602
推荐用-pthread选项(compile and link with -pthread flag)
pthread返回的第一个参数为指向线程标识符的指针,第三个参数为start routine,即线程执行函数的起始地址