资源描述:
《linux高级编程(四、线程互斥与同步)》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、/////////////////////////第四天线程同步/////////////////////////////////////////////////////////////////////////////////多线程同步问题 线程共享进程的资源和地址空间 任何线程对系统资源的操作都会给其他线程带来影响线程共享进程的资源和地址空间,对这些资源进行操作时,必须考虑线程间同步与互斥问题 三种线程同步机制 互斥锁 信号量 条件变量 互斥锁 用简单的加锁方法控制对共享资源的原子操作 只有两种状态:上锁、解锁互斥锁:更适合同时可用的资源是惟一的情况可
2、把互斥锁看作某种意义上的全局变量 在同一时刻只能有一个线程掌握某个互斥锁,拥有上锁状态的线程能够对共享资源进行操作 若其他线程希望上锁一个已经被上锁的互斥锁,则该线程就会挂起,直到上锁的线程释放掉互斥锁为止互斥锁保证让每个线程对共享资源按顺序进行原子操作互斥锁分类 区别在于其他未占有互斥锁的线程在希望得到互斥锁时是否需要阻塞等待 快速互斥锁 ?调用线程会阻塞直至拥有互斥锁的线程解锁为止 ?默认为快速互斥锁 检错互斥锁 ?为快速互斥锁的非阻塞版本,它会立即返回并返回一个错误信息互斥锁主要包括下面的基本函数: 互斥锁初始化:pthread_mutex_ini
3、t() 互斥锁上锁:pthread_mutex_lock() 互斥锁判断上锁:pthread_mutex_trylock() 互斥锁解锁:pthread_mutex_unlock() 消除互斥锁:pthread_mutex_destroy()3.线程的互斥作用是用于互斥(即运行当前的不能运行另一个)实现线程间同时访问共享的资源,避免同时操作pthread_mutex_t//互斥量(锁)类型,用来定义互斥量对互斥量做初始化intpthread_mutex_init(pthread_mutex_t*restrictmutex,constpthread_mutexattr_t*re
4、strictattr);restrictmutex:互斥量的地址,互斥量通过这个函数获取初始值restrictattr:属性,通常为NULL互斥锁与解锁intpthread_mutex_lock(pthread_mutex_t*mutex);//加锁,intpthread_mutex_unlock(pthread_mutex_t*mutex);//解锁mutex:为互斥量的地址例:pthread_mutex_tmutex;//定义互斥量charbuf[1024];void*thr_fn1(void*arg){inti=0;while(1){pthread_mutex_lock(&mu
5、tex);sprintf(buf,"thr_fn1---%d",i++);printf("%s",buf);sleep(8);pthread_mutex_unlock(&mutex);usleep(50000);}return(void*)23;//用return跳出线程}void*thr_fn2(void*arg){inti=0;while(1){pthread_mutex_lock(&mutex);sprintf(buf,"thr_fn2------------------%d",i++);printf("%s",buf);pthread_mutex_unlock
6、(&mutex);usleep(50000);}pthread_exit((void*)24);}intmain(intargc,char**argv){pthread_mutex_init(&mutex,NULL);void*tret;pthread_ttid1,tid2,tid3;pthread_create(&tid1,NULL,thr_fn1,NULL);pthread_create(&tid2,NULL,thr_fn2,NULL);pthread_join(tid2,&tret);pthread_join(tid1,&tret);return0;}4.线程的同步(条件变量)
7、同步:就是线程待某件事件的发生,当等待事件发生时,被等待的线程和事件一起继续执行待待的线程在事件未发生时则挂起。pthread_cond_t是线程同的的条件变量1)对变量进行初始化intpthread_cond_init(pthread_cond_t*restrictcond,constpthread_condattr_t*restrictattr);restrictcond:条件变量restrictattr:属性,通常设为NULL2)线程同步等待函数in