我正在尝试向类函数发送pthread_t
var并且我遇到了问题...我试图通过使用互斥锁来阻止和解除阻塞线程。我很难理解要发送什么。
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <semaphore.h>
#include <synch.h>
using namespace std;
class myCountingSemaphoreUsingBinarySemaphore {
public:
void waitSemaphore(pthread_t *thread)
{
pthread_mutex_lock(*thread);// Makes value 1 (Not Available)
}
void signalSemaphore(pthread_t *thread)
{
pthread_mutex_unlock(*thread); // Makes value 0 (Available)
}
void deleteSemaphore(pthread_t *thread)
{
pthread_mutex_destroy(*thread);// Deletes
}
};
int readerCount;
int database = (rand() / 100); // Number less than 1000
void reader_writer(void);
int main(int argc, char *argv[])
{
myCountingSemaphoreUsingBinarySemaphore obj;
pthread_t mutex1;
pthread_t wrt;
pthread_create(&mutex1, NULL, reader_writer, void);
pthread_create(&wrt, NULL, reader_writer, void);
//----------------------READER------------------------//
do{
cout << "Database Before Read = " << database << endl;
obj.waitSemaphore(&mutex1);//lock
readerCount++;
if (readerCount == 1)
{
obj.waitSemaphore(&wrt);//lock
obj.signalSemaphore(&mutex1);//unlock
//reading is preformed
obj.waitSemaphore(&mutex1); // lock
readerCount--;
}
if(readerCount == 0)
{
obj.signalSemaphore(&wrt);//unlock
obj.signalSemaphore(&mutex1); // unlock
}
cout << "Database After Read = " << database << endl;
}while (true);
//-----------------------WRITER---------------------//
do{
cout << "Database Before Write = " << database << endl;
obj.waitSemaphore(&wrt);//lock
//writing is preformed
database = database + 10;
obj.signalSemaphore(&mutex1);//unlock
cout << "Database After Write = " << database << endl;
}while(true);
pthread_join( mutex1, NULL);
pthread_join( wrt, NULL);
obj.deleteSemaphore(&mutex1);
obj.deleteSemaphore(&wrt);
return 0;
}
void reader_writer (){}