第12章 posix 线程
pthread_create(pthread_t * thread, pthread_attr_t *attr,void *(*founction (void *),void *arg) :建立
pthread_join(): 等待建立的线程结束,并可返回值
pthread_exit(): 结束线程
注: 用gcc 编译时 后跟: -lpthread 就可以.
信号量:
intclude <semaphore.h>
int sem_init( sem_t *sem, int pshared, unsigned int value);
int sem_wait( sem_t * sem); //减少 1
int sem_post( sem_t * sem); //增加 1
互斥量: mutex 是 mutual exclusion 合写.
intclude <pthread.h>
int pthread_mutex_init( pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
int pthread_mutex_lock( pthread_mutex_t *mutex);
int pthread_mutex_unlock( pthread_mutex_t *mutex);
如果已被锁定, 其他调用 lock 时,则阻塞. mutexattr 为NULL时 , 属性为默认值.
使用方法:
1. 先 pthread_mutex_init
2. pthread_create 建立线程.
3 pthread_mutex_lock 和 pthread_mutex_unlock 加锁和开锁
4 pthread_join 结束 线程
5 pthread_mutex_destory 结束 .
用sleep()函数 来实现两个线程加锁和解锁.
线程的属性:
其中:
detached 属性,主线程不用等待子线程的结束.
用法:
pthread_attr_t thread_attr;
res = pthread_attr_init(&thread_attr); // res 返回0 为成功
/*设置属性*/
res = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
/*然后再建立线程*/
res = pthread_create(&a_thread,&thread_attr, thread_function,(void*)arg);
/*结束属性*/
(void) pthread_attr_destory(&thread_attr);
调度属性: ( pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy); )
用法:
声明:
pthread_t a_thread; //use to create pthread
pthread_attr_t thread_attr; //use to initial attributes
int max_priority;
int min_priority;
struct sched_param scheduling_value;
1. res = pthread_attr_init(&thread_attr); //初始化
2. res = pthread_attr_setschedpolicy( &thread_attr, SCHED_OTHRE); //设置属性
3. res = pthread_attr_setdetachstate( &thread_attr, PTHREAD_CREATE_DETACHED);
4. res = pthread_create( &a_thread, &thread_attr, thread_function, (void *) arg); //建立新线程
5. max_priority = sched_get_priority_max( SCHED_OTHER ); //取得优先级范围
6. min_priority = sched_get_priority_min( SCHED_OTHER );
7. scheduling_value.sched_priority = min_priority; //以下是设置新优先级
8. res = pthread_attr_setschedparam( & thread_attr, &scheduling_value); //同上
9. (void) pthread_attr_destroy( &thread_attr); //
取消线程: 用一个线程要求另一个线程终止.
int pthread_cancel(pthread_t thread);
int pthread_setcancelstate(int state, int *oldstate); //在子线程中设置取消状态
其中: state可为: 1, PTHREAD_CANCEL_ENABLE //允许接收取消请求
2,PTHREAD_CANCEL_DISABLE //忽略请求
oldstate: 提取以前的状态,可设置为NULL.
如果 接收到请求, 则
int pthread_setcanceltype( int type, int *oldtype);
type: 1, PTHREAD_CANCEL_ASYNCHRONOUS //立即执行
2, PTHREAD_CANCEL_DEFFERRED
//等待线程执行到了取消点函数再执行, 如: pthread_join, pthread_cond_wait ... 详见 man 7 pthreads 中的
// cancelation points
多线程:
数组方法:for(lots_of_threads = 0; lots_of_threads < NUM_THREADS; lots_of_threads++) {
res = pthread_create(&(a_thread[lots_of_thread]),NULL, thread_function, \
(void *)&lots_of_threads);
if (res != 0) {
perror(“Thread creation failed”);
exit(EXIT_FAILURE);
}
sleep(1);
}