#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
pthread_t child_thread;
pthread_t child_thread2;
typedef struct{
int pass_data1;
int pass_data2;
}PassDataGroup;
void *child_function(void *arg)
{
PassDataGroup *pass = (PassDataGroup *)arg;
printf("this is a child thread. \n");
if(!pass){
printf(" no data passed , I do not need to do anything \n ");
return NULL;
}
printf("this is a child thread. your first passed data is := %d \n", pass->pass_data1);
printf("this is a child thread. your second passed data is := %d \n", pass->pass_data2);
return NULL;
}
int main(int argc, char* argv[])
{
PassDataGroup *pass = (PassDataGroup *)malloc(sizeof(PassDataGroup));
memset(pass, 0, sizeof(PassDataGroup));
pass->pass_data1=1;
pass->pass_data2=2;
pthread_create(&child_thread, NULL, child_function, pass);
//no data pass
//pthread_create(&child_thread, NULL, child_function, NULL);
sleep(3);
return 0;
}
需要注意的是,我们的main线程一定要等到子线程退出后再退出。因为main退出时会终止线程,这样我们的子线程也会停止。
当然,这个等待只限于主线程操作,我们是子线程再次创建子线程,则不用考虑这个结果。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
pthread_t child_thread;
pthread_t child_thread2;
typedef struct{
int pass_data1;
int pass_data2;
}PassDataGroup;
void *child_function2(void *arg)
{
printf("this is a child thread--------------. \n");
sleep(3);
printf("this is a child thread. ----------------- \n");
return NULL;
}
void *child_function(void *arg)
{
PassDataGroup *pass = (PassDataGroup *)arg;
printf("this is a child thread. \n");
if(!pass){
printf(" no data passed , I do not need to do anything \n ");
return NULL;
}
printf("this is a child thread. your first passed data is := %d \n", pass->pass_data1);
printf("this is a child thread. your second passed data is := %d \n", pass->pass_data2);
pthread_create(&child_thread2, NULL, child_function2, NULL);
printf("this is a child thread. I'm exiting \n");
return NULL;
}
int main(int argc, char* argv[])
{
PassDataGroup *pass = (PassDataGroup *)malloc(sizeof(PassDataGroup));
memset(pass, 0, sizeof(PassDataGroup));
pass->pass_data1=1;
pass->pass_data2=2;
pthread_create(&child_thread, NULL, child_function, pass);
//no data pass
//pthread_create(&child_thread, NULL, child_function, NULL);
sleep(5);
return 0;
}
代码可以潇洒运行,结果:
./pthread_create
this is a child thread.
this is a child thread. your first passed data is := 1
this is a child thread. your second passed data is := 2
this is a child thread. I'm exiting
this is a child thread--------------.
this is a child thread. -----------------