标签:tin count abort mutex errors color main read sleep
//pthread_mutex_trylock非阻塞时互斥锁
#include <iostream> #include <pthread.h> #include <ctime> #include "errors.h" #define sun using namespace std; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; const int SPIN=100; long counter; time_t end_time; void *pthread_counter_thread(void*) { while(time(NULL)<end_time) { int status=pthread_mutex_lock(&mutex); if(status) err_abort(status,"Lock mutex"); for(int spin=0;spin<SPIN;++spin) counter++; status=pthread_mutex_unlock(&mutex); if(status) err_abort(status,"Unlock mutex"); sleep(1); } cout<<"Counter is :"<<counter<<endl; return NULL; } void *pthread_monitor_thread(void *) { int status,misses=0; while(time(NULL)<end_time) { sleep(3); status=pthread_mutex_trylock(&mutex); if(status!=EBUSY) { if(status!=0) err_abort(status,"Trylock mutex"); cout<<"Pthread_mutex_trylock,Counter is :" <<counter/SPIN<<endl; status=pthread_mutex_unlock(&mutex); if(status!=0) err_abort(status,"Unlock mutex"); } else misses++; cout<<"Moniter thread missed update :"<<misses<<"times."<<endl; return NULL; } } int main() { #ifdef sun cout<<"Setting concurrency level to 2"<<endl; pthread_setconcurrency(2); #endif pthread_t pthread_counter_id,pthread_monitor_id; end_time=time(NULL)+60; //创建 pthread_counter_thread int status=pthread_create(&pthread_counter_id,NULL,pthread_counter_thread,NULL); if(status) err_abort(status,"Create counter thread"); //创建 pthread_monitor_thread status=pthread_create(&pthread_monitor_id,NULL,pthread_monitor_thread,NULL); if(status) err_abort(status,"Create monitor thread"); //连接 pthread_counter_thread status=pthread_join(pthread_counter_id,NULL); if(status) err_abort(status,"Join counter thread"); //连接 pthread_monitor_thread status=pthread_join(pthread_monitor_id,NULL); if(status) err_abort(status,"Join monitor thread"); return 0; }
1.
pthread_mutex_trylock函数间接性的报告计数器的值,仅当他对计数器的访问与计数线程没有冲突时才发生报告
counter_thread线程在更新计数器时保持互斥量的事件长短,增大该数值使monitor_thread线程中pthread_mutex_trylock函数
返回EBUSY值的概率增大
2.
计数线程每一秒醒来一次,锁住互斥量,计数器的数值增加,计数器,每秒增加SPIN
监控线程每三秒醒来一次,并试图加锁互斥量如果调用返回EBUSY,则监控线程计算失败的次数,然后再次等三秒,如果
pthread_mutex_trylock函数返回成功,则监控线程打印计数器counter当前的值
3.
pthread_setconcurrency(2);设置线程并发级别为2,允许监控线程和计数线程在单处理器中并发执行;
否则监控线程要等计数线程执行完之后才能执行
标签:tin count abort mutex errors color main read sleep
原文地址:https://www.cnblogs.com/tianzeng/p/9157927.html