Linux多线程编程学习代码(代码已上传gitee,还请各位兄弟点个Star哦!)
https://gitee.com/chenshao777/linux_thread.git
笔记:
1.运行代码时 ./a.out 也会被当作是一个参数
2.如果main线程调用了 return 0; 则子线程也会结束
3.main线程调用pthread_exit函数,子线程依然可以运行
4.main线程接受参数的方式是通过argc,argv
5.任意线程调用exit函数都会导致整个进程退出
spu.h文件
#ifndef _SPU_H_
#define _SPU_H_
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#endif
03.main_son_args_thread.c文件
/*
1.子线程传入结构体
2.主线程通过argc,argv传入参数
3.主线程调用pthread_exit函数退出,保证子线程继续运行
*/
#include "spu.h"
struct student
{
int age;
char name[20];
};
void *thread_fun(void *stu)
{
/* 这里如果加sleep,main执行完return后,子线程将得不到执行 */
// sleep(1);
printf("age = %d, name = %s\n", ((struct student*)stu)->age, ((struct student*)stu)->name);
return (void*)0;
}
int main(int argc, char *argv[])
{
int err;
pthread_t thread_id;
struct student stu;
void *__retval;
stu.age = 20;
memcpy(stu.name, "xiaoming", 20);
err = pthread_create(&thread_id, NULL, thread_fun, &stu);
if(err != 0)
printf("create fail, err = %d\n",err);
else
printf("create success!\n");
for(int i = 0; i < argc; i++)
{
printf("args[%d] = %s\n", i, argv[i]);
}
/* 使用该函数退出main线程后,子线程会继续执行 */
pthread_exit(__retval);
}