我有两个类评估线程,但我不能发送信号从一个到另一个,一些想法为什么它不起作用:
第1课:
#include "timer.h"
#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "mutexy.h"
Timer::Timer() {
}
Timer::~Timer() {
}
void Timer::startThread() {
pthread_create(&thread, NULL, runInstance, reinterpret_cast<void *>(this));
}
void Timer::joinThread() {
pthread_join(thread, NULL);
}
void Timer::init() {
this->hh = 0;
this->day = 1;
this->month = 1;
this->year = 2011;
}
void Timer::run() {
while(true)
{
if(hh==24) {
hh = 0;
day++;
if(day==31) {
day=1;
month++;
if(month==13) {
year++;
month==1;
}
}
}
for (int i=0; i<10; i++) {
if(hh==7) {
hh=20;
pthread_cond_signal(&brak_biletow_treshold);
}
}
sleep(1);
hh++;
pthread_yield();
}
}
void* Timer::runInstance(void *instance) {
Timer *d = reinterpret_cast<Timer *>(instance);
d->run();
return NULL;
}
等级2:
#include "flight_list.h"
#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "mutexy.h"
string cities[8] = {"Warszawa","Berlin","Paryz","Londyn","Dublin","Madryt","Wieden","Moskwa"};
FlightList::FlightList() {
srand(time(NULL));
}
FlightList::~FlightList() {
}
void FlightList::startThread() {
pthread_create(&thread, NULL, runInstance, reinterpret_cast<void *>(this));
}
void FlightList::joinThread() {
pthread_join(thread, NULL);
}
void FlightList::init() {
flightTab = new Flight *[10];
for (int i=0; i<10; i++) {
int city = rand()%7+1;
flightTab[i] = new Flight(i*2+2,i+2,1,2011,60,cities[0],cities[city]);
}
}
void FlightList::run() {
while(true)
{
pthread_mutex_lock(&bilety_mutex);
pthread_cond_wait(&brak_biletow_treshold, &bilety_mutex);
for (int i=0; i<10; i++) {
for(int i=0; i<9; i++)
flightTab[i] = flightTab[i+1];
int city = rand()%7+1;
flightTab[9] = new Flight(4,10,2,2011,60,cities[0],cities[city]);
}
pthread_mutex_unlock(&bilety_mutex);
pthread_yield();
}
}
void* FlightList::runInstance(void *instance) {
FlightList *d = reinterpret_cast<FlightList *>(instance);
d->run();
return NULL;
}
和带有mutex和cond_t的头文件:
#include <pthread.h>
static pthread_mutex_t bilety_mutex;
static pthread_mutex_t loty_mutex;
static pthread_cond_t brak_biletow_treshold = PTHREAD_COND_INITIALIZER
互斥锁正在工作,但线程没有收到信号:S
答案 0 :(得分:2)
每个翻译单元都有自己的brak_biletow_treshold
实例,因为您已将它们声明为static
(这有效地将范围限制为当前翻译单元)。
您需要更改声明和访问“全局”的方式。我建议你将条件传递给两个类的构造函数。
答案 1 :(得分:1)
这是因为包含头文件的每个C源文件都会获得静态变量的自己的副本。它们不在翻译单位之间共享。
互斥锁只有似乎才能工作,因为在这种情况下他们的行动不会相互影响。对于互斥锁,看起来它正在发挥作用直到数据被破坏的程度。
对于条件变量,分离意味着它不看起来像是在工作,实际上它不是。
一种解决方案是在头文件声明中标记extern
,在某个C文件中将定义它们标记为:
my_thread_stuff.h:
extern pthread_mutex_t bilety_mutex;
extern pthread_mutex_t loty_mutex;
extern pthread_cond_t brak_biletow_treshold;
global_thread_stuff.c:
#include "my_thread_stuff.h"
pthread_mutex_t bilety_mutex;
pthread_mutex_t loty_mutex;
pthread_cond_t brak_biletow_treshold = PTHREAD_COND_INITIALIZER;