网站建设宣传图片,哪些网站是单页面应用程序,手机如何做微电影网站,网上服务中心临界资源:可以被多个执行流#xff08;线程或者叫轻量级进程#xff09;同是访问的#xff08;多个执行流共享的#xff0c;比如#xff1a;全局、堆等等#xff09;#xff1b;临界区#xff1a;访问这些临界资源的代码#xff1b;原子性#xff1a;没有中间态…临界资源:可以被多个执行流线程或者叫轻量级进程同是访问的多个执行流共享的比如全局、堆等等临界区访问这些临界资源的代码原子性没有中间态不做或者做完
1.展示没有互斥的程序
1.1.一个购票系统有5个线程在购票
#includeiostream
#includecstdio
#includeunistd.h
#includepthread.hint tickets100;
void* thread_run(void* args)
{int tmp*((int*)args);while(1){if(tickets0)//购表{usleep(10000);tickets--;printf(我是%d线程,还剩%d\n,tmp,tickets);}else{printf(没票了\n);break;}}return (void*)0;
}
int main()
{pthread_t tid[5];for(int i0;i5;i)//创建5个线程{int* tnew int(i);pthread_create(tidi,NULL,thread_run,(void*)t);}for(int i0;i5;i){pthread_join(tid[i],NULL);}return 0;
}
执行结果不是每次都会产生这样的结果 把票购成负数了不合理 原理 2.互斥
互斥整个过程保持临界资源的原子性 pthread_mutex_t lock;//锁 pthread_mutex_init(lock,NULL);//初始化 pthread_mutex_lock(lock);//加锁 //临界区 pthread_mutex_unlock(lock);//解锁 pthread_mutex_destroy(lock);//删除锁 修改上面代码
#includeiostream
#includecstdio
#includeunistd.h
#includepthread.hpthread_mutex_t lk;//锁
int tickets100;
void* thread_run(void* args)
{int tmp*((int*)args);while(1){pthread_mutex_lock(lk);//加锁if(tickets0){usleep(10000);tickets--;printf(我是%d线程,还剩%d\n,tmp,tickets);}else{printf(没票了\n);pthread_mutex_unlock(lk);//解锁break;}pthread_mutex_unlock(lk);//解锁}return (void*)0;
}
int main()
{pthread_mutex_init(lk,NULL);//初始化pthread_t tid[5];for(int i0;i5;i){int* tnew int(i);pthread_create(tidi,NULL,thread_run,(void*)t);}for(int i0;i5;i){pthread_join(tid[i],NULL);}pthread_mutex_destroy(lk);//删除锁return 0;
}
3.如何保证锁的原子性互斥的原理
为了实现互斥锁操作,大多数体系结构都提供了swap或exchange指令汇编作用是把寄存器和内存单元的数据相交换
过程每一个线程调用lock会先把自己上下文中关于锁的变量设为0然后和使用一行代码原子性交换上下文的数据和锁的数据锁的数据被换走变成0其它线程来交换还是0会挂起等待循环这个过程直到换走数据的线程解锁为止 如果交换走锁数据的线程时间片到了被调度那么它也是抱着锁走的其他线程还是不能执行临界资源