-
#include "stdio.h"
-
#include "string.h"
-
#include "stdlib.h"
-
#include "pthread.h"
-
#include "unistd.h"
-
-
-
pthread_t ntid;
-
-
void printids(const char *s)
-
{
-
pid_t pid;
-
pthread_t tid;
-
-
pid = getpid();/*获取进程id*/
-
tid = pthread_self();/*获取线程id*/
-
printf("%s pid %d tid %u(0x%x)\n",s,(unsigned int)pid,(unsigned int)tid,(unsigned int)pid);
-
-
}
-
-
void * thr_fn(void *arg)
-
{
-
printids(arg);
-
return NULL;
-
}
-
int main(void)
-
{
-
int err = 0;
-
void * ThreadResult = NULL;
-
-
err = pthread_create(&ntid,NULL,thr_fn,"new thread:");/*创建一个线程*/
-
if(err!=0)
-
{
-
fprintf(stderr,"can't create thread:%s\n",strerror(err));
-
exit(1);
-
}
-
printids("main thread:");/*主线程中的打印*/
-
if(0!=pthread_join(ntid,&ThreadResult))
-
{
-
printf("wait thread fail!\n");
-
}
-
-
return 0;
-
}
编 译:gcc -o pthread_create pthread_create.c -l pthread
运行结果:new thread: pid 11448 tid 3087461264(0x2cb8)
main thread: pid 11448 tid 3087464128(0x2cb8)
阅读(889) | 评论(0) | 转发(0) |