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);