线程
来源:互联网 发布:黑莓passport删除软件 编辑:程序博客网 时间:2024/06/06 00:13
线程---在进程内部,可以将进程分成多个线程,其中,线程的调用是由系统内核调度程序来实现的,每一个线程都具有自己特有的线程号。
1.线程的创建
函数声明:
#include<ppthread.h>
int pthread_create(pthread_t *thread,pthread_attr_t *attr,void *(*start_routine)(void*),void *arg);
pthread_create 用于创建一个新的线程,将其标识符放入teread指向的新线程中
attr 属性对象的指针,用于设置要执行的线程属性
pthread_attr_init()生成属性对象
arg 存放要传递给所调用函数的参数
2.结束线程
pthread_exit函数
#include<prhread.h>
int pthread_exit(void *retval);
调用清楚处理函数,其返回值为retval
3.线程的挂起
#include<prhread.h>
iint pthread_join(pthread_t,void **thread_return);
pthread_join()的调用者将挂起并等待th线程终止,retval是等待终止的线程(ID is th)的返回值,若thread_return不为NULL,则*thread_return=retval
(一个线程只允许唯一的另一个线程使用pthread_join()等待它的终止,并且被等待的线程应该处于join状态(分离状态)。
4.取消线程
当前线程调用函数取消另一个线程
函数声明:
#include<pthread.h>
int pthread_cancel(pthread_t thread);
int pthread_setcancelstate(int state,int *oldstate);
int pthread_setcanceltype(int type,int *oldtype);
void pthread_testcancel(void);
pthread_cancel 用于取消一个线程(由参数thread决定要取消的线程),调用成功时,返回值为0,反之返回错误代码。
pthread_cancel调用并不等待线程终止,它只是提出请求。线程在pthread_cance发出后会继续运行,直到达到Cancellation Point
如下几个POSIX为Cancellation Point
pthread_join
pthread_cond_wait
pthread_cond_timedwait
pthread_testcancel
sem_wait
sigwait
pthread_setcancelstate设置调用函数的线程自身的状态
state 要设置的新的状态
oldstate 指向存放要设置的状态的缓冲区的指针(调用成功时,返回值为0,反之,返回错误代码)
pthread_setcanceltype设置取消的响应方式
PTHREAD_CANCEL_ASYNCHRONOUS立刻取消
PTHREAD_CANCEL_DEFERRED延迟取消至Cancellation Point
type 要设置的方式
oldtype 缓冲区指针(调用成功返回值为0,反之为错误代码)
pthread_testcancel 用于设置Cancellation Point,若请求挂起
,此函数就取消当前线程。
5.互斥
互斥(mutex)是一种相互排斥的锁,对于一个特定的互斥,在同一时刻只能有一个线程给它上锁。是为了使某一资源不能在同一时刻被两个以上的线程同时访问,当另一个线程试图获得锁时,它就会被挂起,直到互斥解锁时为止。
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 线程
- 散列集Hashset ---猜年龄
- 运动和地理位置API
- ios多线程
- js原型链
- Javascript之Function
- 线程
- Netty4.0学习笔记系列之一:Server与Client的通讯
- cocos2dx使用了第三方库照样移植android平台-解决iconv库的移植问题
- 第一个童年游戏“动物棋",开发及移植到android
- hdu acm 1565 方格取数(1)
- PHP一键比对更新MYSQL数据库的一些想法
- hdoj 1027 Ignatius and the Princess II 【全排列】【STL】
- HTML DOM
- Android的错误