#include #include #include #include #include void* aworking(void* arg); struct Test{ int num; int age; }; int main(int argc, char const *argv[]) { struct Test t; pthread_t apid; pthread_create(&apid, NULL, aworking, &t); // pthread_join是一个阻塞函数,需等到子线程执行结束后才能解除阻塞 // 并能接受子线程调用pthread_exit传递的参数 void* ptr; // pthread_join的第二个参数是一个二级指针,即指向内存空间指针的指针 pthread_join(apid, &ptr); struct Test* pt = (struct Test*)ptr; printf("sub thread - num: %d, age: %d\n", pt->num, pt->age); for (size_t i = 0; i < 10; i++) { printf("this is main thread......1, thread id: %ld\n", pthread_self()); } return 0; } void* aworking(void* arg){ int num = 0; for (size_t i = 0; i < 10; i++) { printf("this is aworking thread......%d, thread id: %ld\n", num++, pthread_self()); } // 如果不把Test结构体定义成静态变量或者全局变量,那么当子线程释放后,子线程的栈空间也被释放了,数据就清除了。 //static struct Test t; // 或者在使用主线程的栈空间传递数据到子线程 struct Test* t = (struct Test*)arg; t->num = 100; t->age = 6; // 子线程携带数据退出 pthread_exit(t); return NULL; }