MutexLock.h
/*
* MutexLock.h
* Copyright (C) 2023 zxinlog <zxinlog@126.com>
*
* Distributed under terms of the MIT license.
*/
#ifndef __MUTEXLOCK_H__
#define __MUTEXLOCK_H__
#include <pthread.h>
class MutexLock {
public:
MutexLock();
~MutexLock();
void lock();
void trylock();
void unlock();
private:
pthread_mutex_t _mutex;
};
#endif /* !MUTEXLOCK_H */
MutexLock.cc
/*
*
* Copyright (C) 2023-08-07 10:27 zxinlog <zxinlog@126.com>
*
*/
#include "MutexLock.h"
#include <stdio.h>
#include <pthread.h>
MutexLock::MutexLock() {
int ret = pthread_mutex_init(&_mutex, nullptr);
if (ret) {
perror("pthread_mutex_init");
return;
}
}
MutexLock::~MutexLock() {
int ret = pthread_mutex_destroy(&_mutex);
if (ret) {
perror("pthread_mutex_destroy");
return;
}
}
void MutexLock::lock() {
int ret = pthread_mutex_lock(&_mutex);
if (ret) {
perror("pthread_mutex_destroy");
return;
}
}
void MutexLock::unlock() {
int ret = pthread_mutex_unlock(&_mutex);
if (ret) {
perror("pthread_mutex_destroy");
return;
}
}
void MutexLock::trylock() {
int ret = pthread_mutex_trylock(&_mutex);
if (ret) {
perror("pthread_mutex_destroy");
return;
}
}
test.cc
/*
*
* Copyright (C) 2023-08-07 10:33 zxinlog <zxinlog@126.com>
*
*/
#include <func.h>
#include <iostream>
#include "MutexLock.h"
#define N 1000000
using std::cout;
using std::endl;
int global_num;
void *ThreadFunc(void *arg) {
MutexLock *p_mutex_lock = (MutexLock *) arg;
for (int i = 0; i < N; i++) {
p_mutex_lock->lock();
global_num++;
p_mutex_lock->unlock();
}
pthread_exit(nullptr);
}
int main(int argc, char *argv[]) {
MutexLock mutex_lock;
pthread_t tid;
global_num = 0;
pthread_create(&tid, nullptr, ThreadFunc, &mutex_lock);
for (int i = 0; i < N; i++) {
mutex_lock.lock();
global_num++;
mutex_lock.unlock();
}
pthread_join(tid, nullptr);
cout << "global_num = " << global_num << endl;
return 0;
}