From: http://blog.csdn.net/lanyan822/article/details/7586845
线程的创建
使用pthread_create函数。
#include<pthread.h>
int pthread_create (pthread_t *__restrict __newthread,//新创建的线程ID
__const pthread_attr_t *__restrict __attr,//线程属性
void *(*__start_routine) (void *),//新创建的线程从start_routine开始执行
void *__restrict __arg)//执行函数的参数
返回值:成功-0,失败-返回错误编号,可以用strerror(errno)函数得到错误信息
线程的终止
三种方式
- 线程从执行函数返回,返回值是线程的退出码
- 线程被同一进程的其他线程取消
- 调用pthread_exit()函数退出。这里不是调用exit,因为线程调用exit函数,会导致线程所在的进程退出。
线程同步
线程同步的三种方式:
1、互斥量
互斥量用pthread_mutex_t数据类型来表示。
两种方式初始化,第一种:赋值为常量PTHREAD_MUTEX_INITIALIZER;第二种,当互斥量为动态分配是,使用pthread_mutex_init函数进行初始化,使用pthread_mutex_destroy函数销毁。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
int num=0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
void *add(void *arg) {//线程执行函数,执行500次加法
int i = 0,tmp;
for (; i <50; i++)
{
pthread_mutex_lock(&mylock);
tmp=num+1;
num=tmp;
printf("add+1,result is:%d\n",num);
pthread_mutex_unlock(&mylock);
}
return ((void *)0);
}
void *sub(void *arg)//线程执行函数,执行500次减法
{
int i=0,tmp;
for(;i<50;i++)
{
pthread_mutex_lock(&mylock);
tmp=num-1;
num=tmp;
printf("sub-1,result is:%d\n",num);
pthread_mutex_unlock(&mylock);
}
return ((void *)0);
}
int main(int argc, char** argv) {
pthread_t tid1,tid2;
int err;
void *tret;
err=pthread_create(&tid1,NULL,add,NULL);//创建线程
if(err!=0)
{
printf("pthread_create error:%s\n",strerror(err));
exit(-1);
}
err=pthread_create(&tid2,NULL,sub,NULL);
if(err!=0)
{
printf("pthread_create error:%s\n",strerror(err));
exit(-1);
}
err=pthread_join(tid1,&tret);//阻塞等待线程id为tid1的线程,直到该线程退出
if(err!=0)
{
printf("can not join with thread1:%s\n",strerror(err));
exit(-1);
}
printf("thread 1 exit code %d\n",*((int*)tret));
err=pthread_join(tid2,&tret);
if(err!=0)
{
printf("can not join with thread1:%s\n",strerror(err));
exit(-1);
}
printf("thread 2 exit code %d\n",*((int*)tret));
return 0;
}
2、读写锁
允许多个线程同时读,只能有一个线程同时写。适用于读的次数远大于写的情况。
读写锁初始化:
#include<pthread.h>
int pthread_rwlock_init (pthread_rwlock_t *__restrict __rwlock,
__const pthread_rwlockattr_t *__restrict
__attr);
int pthread_rwlock_destroy (pthread_rwlock_t *__rwlock);
int pthread_rwlock_rdlock (pthread_rwlock_t *__rwlock)
int pthread_rwlock_wrlock (pthread_rwlock_t *__rwlock)
int pthread_rwlock_unlock (pthread_rwlock_t *__rwlock)
3、条件变量
条件变量用pthread_cond_t数据类型表示。
条件变量本身由互斥量保护,所以在改变条件状态前必须锁住互斥量