09,线程

来源:互联网 发布:linux mint和ubuntu 编辑:程序博客网 时间:2024/05/18 19:42

目前主流的操作系统都支持多进程,而在每一个进程的内部又可以支持多线程;
也就是说线程隶属于进程,是进程内部的流程流;

进程是重量级的,新建进程对系统资源的消耗比较大;
而线程是轻量级的,线程会共享所有进程中的资源,但每个线程都有一块独立的栈区;



#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);


第一个参数:用于存放新线程的编号;
第二个参数:用于指定线程的属性,给NULL表示默认属性;
第三个参数:函数指针类型,指向函数,用于设置新线程的处理函数;
第四个参数:作为线程处理函数的实参;

函数功能:主要用于在当前正在调用的进程中启动一个新线程;

返回值:成功返回0;失败返回错误编号;
Compile and link with -pthread.



#include <pthread.h>
pthread_t pthread_self(void);

函数功能:主要用于获取当前正在调用线程的编号并返回;



#include <pthread.h>
int pthread_equal(pthread_t t1, pthread_t t2);
Compile and link with -pthread.

函数功能:主要用于判断两个参数指定的线程编号是否相等;
如果相等则返回非0;不想等返回0;




#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
Compile and link with -pthread.

第一个参数:线程编号
第二个参数:获取目标线程的退出状态信息

返回值:成功返回0;失败返回错误编号;

函数功能:主要用于等待参数retval所指向的线程终止,
一旦参数thread所指向的线程终止了,则该函数立即返回;
当然前提条件是thread所指向的线程允许等待

当第二个参数retval不为空时,该函数会将目标线程终止时退出状态信息拷贝
到*retval所指向的位置上;





#include <pthread.h>
int pthread_detach(pthread_t thread);
Compile and link with -pthread.

函数功能:主要用于将参数指定的线程设置为分离状态;
当分离状态的线程终止时,会自动释放资源给系统,
无法被其他线程调用prhread_join函数所等待;






*********线程的终止和取消***********
#include <pthread.h>
void pthread_exit(void *retval);
Compile and link with -pthread.

函数功能:主要用于终止当前正在调用的线程,通过参数返回该线程的退出状态信息;该退出状态信息可以被同一个进程中的其他线程通过调用pthread_join函数进行获取;




#include <pthread.h>
int pthread_cancel(pthread_t thread);
Compile and link with -pthread.

函数功能:主要用于给参数指定的进程发送取消的请求
比如终止子线程中的死循环;


===============================================

线程的同步:
当多个线程在同一时间同时访问同一种共享资源时,可能会造成数据的覆盖和不一致等问题;
此时需要对多个线程进行协调,线程之间的协调和通信就叫做线程之间的同步问题;





实现互斥量实现线程的同步:
1.定义互斥量
    pthread_mutex_t mutex;

2.初始化互斥量
    pthread_mutex_init(&mutex,NULL);
    
3.使用互斥量进行加锁
    pthread_mutex_lock(&mutex);
    
4.访问共享资源
    
5.使用互斥量进行解锁
    pthread_mutex_unlock(&mutex);
    
6.如果不再使用,则销毁
    pthread_mutex_destroy(&mutex);
    





**************************************
#include <semaphore.h>
使用信号量实现线程的同步

用于控制同时访问同一种共享资源的进程/线程个数;

1.定义信号量
    sem_t sem;

2.初始化信号量
    sem_init(&sem,0,初始值);

3.获取信号量,也就是信号量减1
    sem_wait(&sem);

4.访问共享资源

5.释放信号量,也就是信号量加1
    sem_post(&sem);

6.如果不再使用,则销毁信号量
    sem_destroy(&sem);
0 0
原创粉丝点击