目录
1.linux线程
1.1 基本介绍
线程是计算机独立运行的最小单位,也可以看出线程是系统分配CPU资源的基本单位,每个线程在系统给它时间片内,取得CPU的控制权,执行线程中的代码。
相对于进程来说,线程创建消耗资源少,线程切换速度快,进程内的线程数据共享,通信效率高。
1.2 线程信息
线程ID,每个线程有唯一的线程ID
寄存器,如PC计数器,堆栈指针等
堆栈
信号掩码
优先级
线程私有空间等。
1.3 线程创建
#include <pthread.h>
typedef struct
{
int detachstate; /*<!与进程脱离同步状态*/
int schedpolicy; /*<!线程调度策略*/
struct sched_param schedparam; /*<!线程运行优先级等参数*/
int inheritsched; /*<!线程是否显示指定参数和调度策略*/
int scope; /*<!线程竞争CPU范围 (cpu内、进程内)*/
size_t guardsize; /*<!警戒堆栈大小*/
int stackaddr_set; /*<!堆栈地址集*/
void* stackaddr; /*<!堆栈地址*/
size_t stacksize; /*<!堆栈地址大小*/
}pthread_attr_t;
/* @desp, 创建线程
* @param,thread,创建返回的线程ID
* @param,attr,指定线程属性
* @param,start_routine,线程函数
* @param,arg,向线程函数传递的参数
* @return, 0,表示创建成功,否则失败
*/
int pthread_create(pthread_t *thread,pthread_attr_t* attr,void* (*start_routine)(void*),void *arg);
/* @desp, 获取线程Id
* @return,线程ID
*/
pthread_t pthread_self(void);
/* @desp, 比较两个线程ID是否指向同一线程
* @return,0 一样
*/
int pthread_equal(pthread_t thread1,pthread_t thread2);
/* @desp, 保证init_routine 线程函数在进程中执行一次
* @return,0执行成功
*/
int pthread_once(pthread_once_t* once_control,void (*int_routine)(void));
/*create_thread.c example*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int* thread_routine(void* arg);
int main(void)
{
pthread_t thid;
printf("main thread id is %u \r\n",pthread_self());
if (pthread_create(&thid,NULL,(void*)thread_routine,NULL) != 0)
{
printf("thread create failed! \r\n");
exit(1);
}
sleep(1);
exit(0);
}
int* thread_routine(void* arg);
{
pthread_t thid;
thid = pthread_self();
printf("routine thread id is %u \r\n",thid);
return NULL;
}
1.4 线程终止
1> 从线程函数中,通过return返回终止;
2> 调用pthread_exit() 终止线程。
线程终止时的资源释放,如下成对出现的红函数,可以跟着线程的终止而释放资源
#include <pthread.h>
#define pthread_cleanup_push(routine,arg) \
{ struct _pthread_cleanup_buffer buffer; \
_pthread_cleanup_push(&buffer,(routine),(arg));
#define pthread_cleanup_pop \
_pthread_cleanup_pop(&buffer,(routine));}
线程间的同步等待
#include <pthread.h>
/*@desp,线程退出
*
*/
void pthread_exit(void* ret);
/*@desp,挂起自己,等待一个线程结束,
* 一个线程仅仅允许一个线程

最低0.47元/天 解锁文章
506

被折叠的 条评论
为什么被折叠?



