Linux C 线程基础及多线程相关基础函数理解

摘要:

         本次内容是关于Linux C下的线程基础以及多线程中相关函数的用法,并且都有一些简单的例子来帮助大家理解。

目录

1、线程基础

概念

线程的共有资源和私有资源

线程相关api函数(系统调用)

创建线程

线程收尸

结束当前进程

结束另一个线程的执行

获取线程的ID

设置线程的属性

2、线程同步和互斥

同步----信号量

线程互斥


       

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");
		
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值