Demo
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
struct thrd
{
int var;
char str[256];
};
void sys_err(const char *str)
{
perror(str);
exit(1);
}
void *tfn(void *arg)
{
int i = (int)arg;
struct thrd *tval;
tval = malloc(sizeof(tval));
tval->var = i;
strcpy(tval->str, "hello thread");
printf("---I'm child %d, pid = %d, tid = %lu\n", i+1, getpid(), pthread_self());
sleep(i);
return (void *)tval;
}
int main(int argc, char *argv[])
{
pthread_t tid[5];
struct thrd *retval[5];
int i, j, ret;
for(i = 0; i < 5; i++)
{
ret = pthread_create(&tid[i], NULL, tfn, (void *)i);
if(ret != 0) sys_err("pthread_create error");
}
for(j = 0; j < 5; j++)
{
ret = pthread_join(tid[j], (void **)&retval[j]);
if(ret != 0) sys_err("pthread_join error");
printf("child thread %d exit with var = %d, str = %s\n", j+1, retval[j]->var, retval[j]->str);
}
if(i == 5)
{
printf("I'm main, pid = %d, tid = %lu\n", getpid(), pthread_self());
}
return 0;
}
执行结果
---I'm child 1, pid = 4278, tid = 140318439139072
---I'm child 2, pid = 4278, tid = 140318430746368
---I'm child 4, pid = 4278, tid = 140318422353664
---I'm child 3, pid = 4278, tid = 140318288135936
---I'm child 5, pid = 4278, tid = 140318413960960
child thread 1 exit with var = 0, str = hello thread
child thread 2 exit with var = 1, str = hello thread
child thread 3 exit with var = 2, str = hello thread
child thread 4 exit with var = 3, str = hello thread
child thread 5 exit with var = 4, str = hello thread
I'm main, pid = 4278, tid = 140318447634240