- #include<stdio.h>
- #include<pthread.h>
- #include<string.h>
- #include<sys/types.h>
- #include<unistd.h>
- 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_fn1(void *arg)
- {
- printids("new pthread:");
- printf("thread 1 return \n");
- return ((void *)1);
- }
- int main(void)
- {
- int err=0;
- pthread_t tid1,tid2;
- void *tret;
- err=pthread_create(&tid1,NULL,thr_fn1,NULL);
- if(err!=0)
- {
- printf("can't create\n");
- }
- err=pthread_join(tid1,&tret);
- if(err!=0)
- printf("can't join with pthread 1",strerror(err));
- printf("pthread exit code %d\n",(int)tret);
- printids("main pthread:");
- //getchar();
- sleep(1);
- return 0;
- }
输出:
[omcbo@DGSERNMC111 Privacy]$ ./pthead
new pthread: pid 23532 tid 3078073200 (0xb777ab70)
thread 1 return
pthread exit code 1
main pthread: pid 23532 tid 3078076624 (0xb777b8d0)
由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
gcc -o pthread -lpthread pthread.c
阅读(2020) | 评论(0) | 转发(2) |