, когда я пытаюсь использовать mutex
с RAII.Конструктор и деструктор в многопоточном режиме
class MutexLock
{
public:
MutexLock() {
pthread_mutex_init(&mutex_, NULL);
cout << "construct of MutexLock" << endl;
}
~MutexLock() {
cout << "deconstruct of MutexLock" << endl;
pthread_mutex_destroy(&mutex_);
}
void lock() {
pthread_mutex_lock(&mutex_);
}
void unlock() {
pthread_mutex_unlock(&mutex_);
}
private:
MutexLock(const MutexLock &);
MutexLock& operator=(const MutexLock &);
pthread_mutex_t mutex_;
};
class MutexLockGuard
{
public:
explicit MutexLockGuard(MutexLock &mutex): mutex_(mutex) {
cout << "construct of MutexLockGuard" << endl;
mutex_.lock();
}
~MutexLockGuard() {
cout << "deconstruct of MutexLockGuard" << endl;
mutex_.unlock();
}
private:
MutexLockGuard(const MutexLock &);
MutexLockGuard& operator=(const MutexLock &);
MutexLock &mutex_;
};
MutexLock mutex;
int cnt = 5;
void *f(void *arg){
long t_num = (long) arg;
while(true){
MutexLockGuard lock(mutex);
if(cnt>0){
usleep(1);
cout << "args: " << t_num << " " << "cnt: " << cnt-- << endl;
}
else{break;}
}
return NULL;
}
int main()
{
pthread_t tid, tid1, tid2, tid3;
int ret = pthread_create(&tid, NULL, f,(void*)11);
if(ret == -1){
perror("create error\n");
}
ret = pthread_create(&tid1, NULL, f, (void*)22);
if(ret == -1){
perror("create error\n");
}
ret = pthread_create(&tid2, NULL, f, (void*)33);
if(ret == -1){
perror("create error\n");
}
ret = pthread_create(&tid3, NULL, f, (void*)44);
if(ret == -1){
perror("create error\n");
}
pthread_join(tid, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
return 0;
}
Результат показывает, как
construct of MutexLock
construct of MutexLockGuard
construct of MutexLockGuard
construct of MutexLockGuard
construct of MutexLockGuard
args: 11 cnt: 5
deconstruct of MutexLockGuard
construct of MutexLockGuard
args: 11 cnt: 4
deconstruct of MutexLockGuard
construct of MutexLockGuard
args: 11 cnt: 3
deconstruct of MutexLockGuard
construct of MutexLockGuard
args: 11 cnt: 2
deconstruct of MutexLockGuard
construct of MutexLockGuard
args: 11 cnt: 1
deconstruct of MutexLockGuard
construct of MutexLockGuard
deconstruct of MutexLockGuard
deconstruct of MutexLockGuard
deconstruct of MutexLockGuard
deconstruct of MutexLockGuard
deconstruct of MutexLock
Когда четыре нити созданы четыре экземпляра MutexLockGuard
созданы. Но почему поток args: 11
разрушен, а время жизни других трех потоков до тех пор, пока основной поток?
Что вы хотите сказать? «Я не понимаю», это не вопрос. Потратьте больше времени на понимание, а затем приходите к нам с вопросом. Мы не являемся наставниками или преподавателями; это профессиональный Q & A !!!!!!!!!!!!! –
inb4 да, я знаю об иронии повторяющихся восклицательных знаков –