-
#include "stdio.h"
-
#include "string.h"
-
#include "pthread.h"
-
#include "unistd.h"
-
#include "stdlib.h"
-
-
-
void * thr_fn1(void *arg)
-
{
-
printf("thread 1 returning\n");
-
return (void *)1;
-
}
-
-
void * thr_fn2(void *arg)
-
{
-
printf("thread 2 returning\n");
-
return (void *)2;
-
}
-
-
void * thr_fn3(void *arg)
-
{
-
while(1)
-
{
-
printf("thread 3 writing\n");
-
sleep(1);
-
}
-
}
-
-
int main(void)
-
{
-
pthread_t tid = 0;
-
void *tret = NULL;
-
-
pthread_create(&tid,NULL,thr_fn1,NULL);
-
pthread_join(tid,&tret);
-
printf("thread 1 exit code %d\n",tret);
-
-
pthread_create(&tid,NULL,thr_fn2,NULL);
-
pthread_join(tid,&tret);
-
printf("thread 2 exit code %d\n",tret);
-
-
pthread_create(&tid,NULL,thr_fn3,NULL);
-
sleep(3);
-
pthread_cancel(tid);/*强制结束thr_fn3*/
-
pthread_join(tid,&tret);
-
printf("thread 2 exit code %d\n",tret);
-
-
return 0;
-
}
编 译:gcc -o pthread_create pthread_create.c -l pthread
运行结果:
thread 1 returning
thread 1 exit code 1
thread 2 returning
thread 2 exit code 2
thread 3 writing
thread 3 writing
thread 3 writing
thread 2 exit code -1
阅读(555) | 评论(0) | 转发(0) |