【发布时间】:2011-04-11 16:49:26
【问题描述】:
我在从主程序调用函数时遇到问题。
这些功能必须在我的课堂上。
如何从我的 int main() 访问它们?
#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_mutex_t *thread)
{
pthread_mutex_lock(*thread);// Makes value 1 (Not Available)
}
void signalSemaphore(pthread_mutex_t *thread)
{
pthread_mutex_unlock(*thread); // Makes value 0 (Available)
}
void deleteSemaphore(pthread_mutex_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_mutex_t mutex1;
pthread_mutex_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 () {}
这是我得到的错误:
他们需要是什么类型的? pthread_mutex_t_create?还是 pthread_t_create?
什么是正确的类型?
【问题讨论】:
-
能否请您减少您的示例或至少添加您遇到的错误
-
那么您到底遇到了哪一行?或者你想在哪里调用哪个函数?
-
我希望你的编译器不接受这个。
pthread_t是线程类型,而不是互斥类型。您正在寻找pthread_mutex_t。man pthreads. -
@ohlegend,你没有。
pthread_t代表一个线程。pthread_mutex_t代表一个互斥体。pthread_cond_t表示条件变量。您似乎对这些概念感到困惑。我建议您阅读有关这些概念的更多内容,然后特别关注一些有关 pthread 的教程。 -
您不使用 pthreads_mutex_t 创建线程,而是使用 pthread_create。在开始编写项目之前,请最好阅读一些 pthread 教程并创建一些简单的示例。这个教程看起来不错computing.llnl.gov/tutorials/pthreads
标签: c++ class unix g++ pthreads