list8-1.cpp

来自「这是c++编程方面的名著的例子代码」· C++ 代码 · 共 71 行

CPP
71
字号
// Listing 8-1// This program demonstrates the improper use// use of a global mutex to protect a object// two threads#include <iostream.h>#include <pthread.h>#include <mtration.h>#include <math.h>rational Number;pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;void *threadA(void *X){    long int Q;    try{         for(Q =2; Q < 500;Q += 4)         {                pthread_mutex_lock(&Mutex);             Number.assign((Q/2),Q);             cout << pthread_self() << " Thread A: " << Number << endl;             pthread_mutex_unlock(&Mutex);         }    }    catch(general_exception &M)    {      cout << pthread_self() << M.message() << endl;    }                 }//Thread B is not cooperating with the proper// use of Mutex protection for the rational object 'Number'.void *threadB(void *X){   long int Y;   try{       for(Y = 5;Y < 500;Y += 5){           Number.assign((Y/5),Y);           cout << pthread_self() << " Thread B " << *Number << endl;                 }     }   catch(general_exception &M)   {       cout << pthread_self() << M.message() << endl;   }}void main(void){    pthread_t ThreadA;    pthread_t ThreadB;      pthread_create(&ThreadA,NULL,threadA,NULL);    pthread_create(&ThreadB,NULL,threadB,NULL);           pthread_join(ThreadA,NULL);    pthread_join(ThreadB,NULL);    pthread_mutex_destroy(&Mutex);   }         

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?