一、什么是互斥量
#include <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);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
下面以一个简单的多线程程序来演示如何使用互斥量来进行线程同步。在主线程中,我们创建子线程,并把数组msg作为参数传递给子线程,然后主线程调用函数pthread_mutex_lock对互斥量加锁,等待输入,输入完成后,调用函数pthread_mutex_unlock对互斥量解锁,从而使线程函数中的对互斥量加锁的pthread_mutex_lock函数返回并执行子线程中的代码。线程函数在把字符串的小写字母变成大写并统计输入的字符数量之后,它调用pthread_mutex_unlock对互斥量解锁,使主线程能够继续获得互斥量(即对其加锁函数返回),再次执行输入功能直到主线程再次调用pthread_mutex_unlock对其解锁,一直如此重复,直到输入end。
http://leshou.com/zdh2011/tags/%E5%8D%97%E6%98%8C%E5%AD%90%E5%AE%AB%E8%82%8C%E7%98%A4%E4%B8%93%E7%A7%91%E5%8C%BB%E9%99%A2%E6%9C%89%E5%93%AA%E4%BA%9B
http://leshou.com/zdh2011/tags/%E5%8D%97%E6%98%8C%E6%B2%BB%E5%A5%BD%E5%AE%AB%E9%A2%88%E7%B3%9C%E7%83%82%E8%A6%81%E8%8A%B1%E5%A4%9A%E5%B0%91%E9%92%B1
http://leshou.com/zdh2011/tags/%E5%8D%97%E6%98%8C%E6%B2%BB%E7%96%97%E5%AE%AB%E9%A2%88%E7%B3%9C%E7%83%82%E9%9C%80%E8%A6%81%E5%A4%9A%E5%B0%91%E9%92%B1
http://leshou.com/zdh2011/tags/%E5%8D%97%E6%98%8C%E7%9C%8B%E5%AE%AB%E9%A2%88%E7%B3%9C%E7%83%82%E5%93%AA%E4%B8%AA%E5%8C%BB%E9%99%A2%E4%BE%BF%E5%AE%9C
http://leshou.com/zdh2011/tags/%E5%8D%97%E6%98%8C%E8%AF%8A%E6%B2%BB%E5%AE%AB%E9%A2%88%E7%B3%9C%E7%83%82%E4%B8%80%E8%88%AC%E4%BB%B7%E6%A0%BC%E6%98%AF%E5%A4%9A%E5%B0%91
转载于:https://blog.51cto.com/7920753/1296393