Linux操作系统应用程序设计——线程


前言

1、由于新建进程就会创建新的数据段、代码段、堆栈段等,增大了操作系统的开销,为了提高效率,系统引入了线程,也称轻量级进程
2、新建一个线程,它会共享进程所拥有的资源和地址空间,只会新建一个线程对应栈区,相比于进程的完全复制,线程对系统的开销要小得多


一、线程的相关函数

1、pthread_create函数

功能:创建线程

头文件:
#include<pthread.h>
函数原型:
int pthread_create(pthread_t *thread,pthread_attr_t *attr,void*(*start_routine)(void *),void *arg);
参数:
thread:线程标识符
attr:线程属性设置,NULL表示默认属性
start_routine:线程执行函数,参数和返回值都是void *
arg:传递给strat_routine的参数
例子:
#include <stdio.h>
#include <pthread.h>
void *fun(void *p)
{
	while(1)
	{
		printf("thread is running\n");
		sleep(1);
	}
}
int main()
{
	pthread_t id;
	pthread_create(&id, NULL, fun, NULL);
	while(1)
	{
		printf("main is running\n");
		sleep(1);
	}
}

2、pthread_exit函数

功能:退出线程

头文件:
#include<pthread.h>
函数原型:
void pthread_exit(void *retval);
参数:
retval:线程结束时状态,通常是NULL
例子:
pthread_exit(NULL);

3、pthread_join函数

功能:阻塞等待指定线程结束,并回收其资源

头文件:
#include<pthread.h>
函数原型:
int pthread_join(pthread_t thread,void **thread_result);
参数:
thread:等待的线程标识符
thread_result:用来接收线程状态,一般为NULL
例子:
pthread_t id;
pthread_join(id, NULL);

二、互斥锁

原因:由于一个进程可以有多个线程,线程共享进程资源,当两个线程同时访问一个共享资源就会出现互斥

1、pthread _mutex_init函数

功能:互斥锁初始化

头文件:
#include<pthread.h>
函数原型:
int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutexattr_t *mutexattr);
参数:
mutex:互斥锁
Mutexattr:互斥锁属性,NULL为默认属性
例子:
pthread_mutex_t mutex;//定义互斥锁
pthread_mutex_init(&mutex, NULL);//初始化互斥锁

2、pthread _mutex_lock函数

功能:加锁,不成功则阻塞

头文件:
#include<pthread.h>
函数原型:
int pthread_mutex_lock(pthread_mutex_t *mutex);
参数:
mutex:互斥锁
例子:
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);

3、pthread _mutex_unlock函数

功能:解锁

头文件:
#include<pthread.h>
函数原型:
int pthread_mutex_unlock(pthread_mutex_t *mutex);
参数:
mutex:互斥锁
例子:
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_unlock(&mutex);

4、pthread _mutex_destroy函数

功能:删除互斥锁

头文件:
#include<pthread.h>
函数原型:
int pthread_mutex_destroy(pthread_mutex_t *mutex);
参数:
mutex:互斥锁
例子:
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_destroy(&mutex);

三、信号量

也是解决互斥问题的一种方法

1、sem_init函数

功能:初始化信号量

头文件:
#include<semaphore.h>
函数原型:
int sem_init(sem_t *sem,int pshared,unsigned int value);
参数:
sem:信号量对象
pshared:一般为0
value:信号量初始化值
例子:
sem_t sem;//定义一个信号量
sem_init(&sem, 0, 3);//初始化信号量, 共享资源有3个

2、sem_wait函数

功能:信号量大于0,则将信号量减1;信号量为0时,阻塞

头文件:
#include<pthread.h>
函数原型:
int sem_wait(sem_t *sem);
例子:
sem_t sem;
sem_init(&sem, 0, 3);
sem_wait(sem);

3、sem_post函数

功能:信号量加1

#include<pthread.h>
函数原型:
int sem_post(sem_t *sem);
例子:
sem_t sem;
sem_init(&sem, 0, 3);
sem_post(sem);

4、sem_destroy函数

功能:删除信号量

#include<pthread.h>
函数原型:
int sem_destroy(sem_t *sem);
例子:
sem_t sem;
sem_init(&sem, 0, 3);
sem_destroy(sem);

总结

1、由于线程间存在着共享资源,两个线程之间可以实现一些简单的通信
2、但是进程之间是完全独立,两个进程之间能否进行通信呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值