写个函数来解决多线程同时读写一个文件的问题?

RT 用php写 啊
2024-11-17 02:23:09
推荐回答(1个)
回答1:

class Mutex
{
protected:
void *mutex_handler;

public:
// Constructure
Mutex()
{
mutex_handler = new pthread_mutex_t;
pthread_mutex_init((pthread_mutex_t *)mutex_handler, 0);
}

// DeConstructure
inline virtual ~Mutex()
{
if (mutex_handler)
{
pthread_mutex_destroy((pthread_mutex_t *)mutex_handler);
delete (pthread_mutex_t*)mutex_handler;
}
}

void MutexLock(void)
{
pthread_mutex_lock((pthread_mutex_t *)mutex_handler);
}

void MutexUnLock(void)
{
pthread_mutex_unlock((pthread_mutex_t *)mutex_handler);
}
};

// gobal interface for Mutex
struct Guard : public Mutex
{
explicit Guard(void *Handler)
{
Mutex::mutex_handler = Handler;

MutexLock();
}

inline virtual ~Guard()
{
MutexUnLock();
}
};