摘要:
本次内容是关于Linux C下的线程基础以及多线程中相关函数的用法,并且都有一些简单的例子来帮助大家理解。
目录
1、线程基础
概念
线程在进程的空间中的一个任务,对应一个线程函数,它是线程函数的一次执行过程。
线程的共有资源和私有资源
1、对于一个进程中的多个线程,以下为线程公有资源:
可执行的指令(.text)
静态数据(.rodata,.data,.bss)
进程中打开的文件描述符
信号处理函数
当前工作目录
用户ID
用户组ID
2、线程私有资源 :
线程ID (TID)
PC(程序计数器)和相关寄存器
堆栈
局部变量
返回地址
错误号 (errno)
信号掩码和优先级
执行状态和属性
线程相关api函数(系统调用)
创建线程
#include <pthread.h>
Compile and link with -pthread.
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *),
void *arg);
//参数1 ----- 线程ID的指针
//参数2 ----- 线程的属性,默认属性:NULL
//参数3 ----- 线程要执行的函数(线程函数),必须按下面的格式定义
void* xxx(void* arg)
{
......
......
}
//参数4 ----- 传给线程的参数
//返回值 --- 成功:0,失败: 错误码
例如:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
//子线程
void* fun(void*arg)
{
int i;
for(i = 0; i < 7; i++){
printf("this is a function!\n");
sleep(1);
}
return 0;
}
int main(int argc,char **argv)
{
int i;
pthread_t tid;
//fun();
//创建线程
if(pthread_create(&tid,NULL,fun,NULL)){
perror("pthread_create");
exit(1);
}
for(i = 0; i < 7; i++){
printf("this is a main!\n");
sleep(1);
}
return 0;
}
//给线程函数传递参数
例如:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
struct student{
int sno;
char name[20];
float score;
};
//子线程
void* fun(void*arg)
{
struct student * p = (struct student*)arg;
printf("%d %s %.2f\n",p->sno,p->name,p->score);
//printf("%d\n",*(int*)arg);
//printf("%s\n",(char*)arg);
return 0;
}
int main(int argc,char **argv)
{
pthread_t tid;
//int a = 120;
//char str[] = "hello world";
struct student st = {1001,"jack",98.4};
//创建线程
//if(pthread_create(&tid,NULL,fun,&a)){
//if(pthread_create(&tid,NULL,fun,str)){
if(pthread_create(&tid,NULL,fun,&st)){
perror("pthread_create");