php律师网站源码,免费推广软件平台,网站建设 程序开发,网站备案审批号c 老古董 文章目录 c 老古董pthread_mutex概念常用apipthread_mutex_initpthread_mutex_lockpthread_mutex_trylockpthread_mutex_unlockpthread_mutex_destroy 案例 pthread_mutex
概念
互斥锁 mutex是一种简单的加锁的方法来控制对共享资源的访问#xff0c;mutex只有两种…c 老古董 文章目录 c 老古董pthread_mutex概念常用apipthread_mutex_initpthread_mutex_lockpthread_mutex_trylockpthread_mutex_unlockpthread_mutex_destroy 案例 pthread_mutex
概念
互斥锁 mutex是一种简单的加锁的方法来控制对共享资源的访问mutex只有两种状态,即 上锁(lock) 解锁(unlock)。 在访问该资源前首先应申请mutex 如果mutex处于lock状态则默认阻塞申请者。 如果mutex处于unlock状态则会申请到mutex并立即lock unlock操作应该由lock者进行
常用api
pthread_mutex_init
静态分配
pthread_mutex_t mutex PTHREAD_MUTEX_INITIALIZER;动态分配
int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutexattr_t *attr);pthread_mutex_t mutex;pthread_mutex_init(mutex, NULL);功能
初始化一个互斥锁。
参数
mutex指定的互斥锁 互斥锁地址。attr互斥锁的属性NULL 为默认的属性。
返回值
成功返回 0失败返回非 0。
pthread_mutex_lock
#include pthread.h int pthread_mutex_lock(pthread_mutex_t *mutex); 功能
对互斥锁上锁若已经上锁则调用者一直阻塞到互斥锁解锁
参数
mutex指定的互斥锁 互斥锁地址。
返回值
成功返回 0失败返回非 0。
pthread_mutex_trylock
#include pthread.h int pthread_mutex_trylock(pthread_mutex_t *mutex);功能
对互斥锁上锁若已经上锁则上锁失败函数立即返回。
参数
mutex指定的互斥锁 互斥锁地址。
返回值
成功返回 0失败返回非 0。
pthread_mutex_unlock
#include pthread.hint pthread_mutex_unlock(pthread_mutex_t * mutex);功能
对指定的互斥锁解锁。
参数
mutex互斥锁地址。
返回值
成功返回 0,失败返回非 0。
pthread_mutex_destroy
在所有使用过此互斥锁的线程都不再需要使用时候应调用pthread_mutex_destroy销毁互斥锁
pthread_mutex_t mymutex;
pthread_mutex_init(mymutex, NULL);// 当互斥锁使用完毕后要销毁
pthread_mutex_destroy(mymutex);案例
两人公用同一银行账户。
#include stdio.h
#include stdlib.h
#include unistd.h
#include pthread.h//通过互斥锁解决线程间互斥问题int money 10000;//第一步创建互斥锁(由于两个线程操作同一个互斥锁所以定义在全局更加方便一点)
pthread_mutex_t mymutex;void *pthread_fun1(void *arg)
{int get, rest, actual;get 10000;//第三步对共享资源的操作进行上锁pthread_mutex_lock(mymutex);printf(张三正在查询余额...\n);sleep(1);rest money;printf(张三正在取钱...\n);sleep(1);if(get rest){actual 0;}else {actual get;rest rest - get;money rest;}printf(张三想取%d元实际取了%d元余额为%d元\n, get, actual, rest);//第四步当共享资源的操作执行完毕后对互斥锁执行解锁操作pthread_mutex_unlock(mymutex);pthread_exit(NULL);
}void *pthread_fun2(void *arg)
{int get, rest, actual;get 10000;//第三步对共享资源的操作进行上锁pthread_mutex_lock(mymutex);printf(李四正在查询余额...\n);sleep(1);rest money;printf(李四正在取钱...\n);sleep(1);if(get yu){actual 0;}else {actual get;rest rest - get;money rest;}printf(李四想取%d元实际取了%d元余额为%d元\n, get, actual, rest);//第四步当共享资源的操作执行完毕后对互斥锁执行解锁操作pthread_mutex_unlock(mymutex);pthread_exit(NULL);
}int main(int argc, char const *argv[])
{//第二步初始化互斥锁pthread_mutex_init(mymutex, NULL);pthread_t thread1, thread2;if(pthread_create(thread1, NULL, pthread_fun1, NULL) ! 0){perror(fail to pthread_create);exit(1);}if(pthread_create(thread2, NULL, pthread_fun2, NULL) ! 0){perror(fail to pthread_create);exit(1);}pthread_join(thread1, NULL);pthread_join(thread2, NULL);//第五步当互斥锁使用完毕后要销毁pthread_mutex_destroy(mymutex);return 0;
}