1、循环创建多个子线程
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
void *thrd_func(void *arg)
{
int i = (int)arg;
sleep(i);
printf("In thread, thread%d = %lu, PID =%u\n", i+1, pthread_self(), getpid());
return NULL;
}
int main()
{
pthread_t tid;
int ret, i;
for(i = 0; i < 5; i++)
{
ret = pthread_create(&tid, NULL, thrd_func, (void *)i);//注意i值的使用
if(ret != 0)
{
fprintf(stderr, "pthread_create error: %s\n", strerror(ret));
exit(1);
}
}
sleep(i);
return 0;
}
2、pthread_join的使用例子
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thr_fn1(void *arg)
{
printf("thread 1 returning\n");
return (void *)1;
}
void f(void)
{
printf("thread 2 exiting\n");
pthread_exit((void *)2);
}
void *thr_fn2(void *arg)
{
f();
while(1)
{
;
}
}
void *thr_fn3(void *arg)
{
while(1)
{
printf("thread 3 writing\n");
sleep(1);
}
}
int main(void)
{
pthread_t tid;
void *tret;
pthread_create(&tid, NULL, thr_fn1, NULL);
pthread_join(tid, &tret);
printf("thread 1 exit code %d\n", (int)tret);
pthread_create(&tid, NULL, thr_fn2, NULL);
pthread_join(tid, &tret);
printf("thread 2 exit code %d\n", (int)tret);
pthread_create(&tid, NULL, thr_fn3, NULL);
sleep(3);
pthread_cancel(tid);
pthread_join(tid, &tret);
printf("thread 3 exit code %d\n", (int)tret);
return 0;
}