class Buffer { public: Buffer() { num = 0; head = 0; tail = 0; mutex = CreateSemaphore(NULL, 1, 1, NULL); semaphore_white_cell = CreateSemaphore(NULL, buffer_size, buffer_size, NULL); semaphore_black_cell = CreateSemaphore(NULL, 0, buffer_size, NULL); } ~Buffer() { CloseHandle(mutex); } bool put(int x) { WaitForSingleObject(semaphore_white_cell, INFINITE); WaitForSingleObject(mutex, INFINITE); cout << "thread " << GetCurrentThreadId() << " put " << x << "\t"; if (num == buffer_size) { cout << "failed" << endl; ReleaseSemaphore(mutex, 1, NULL); return false; } cells[tail] = x; tail = (tail + 1) % buffer_size; cout << "ok" << endl; num++; ReleaseSemaphore(mutex, 1, NULL); ReleaseSemaphore(semaphore_black_cell, 1, NULL); return true; } bool get(int* p) { WaitForSingleObject(semaphore_black_cell, INFINITE); WaitForSingleObject(mutex, INFINITE); cout << "thread" << GetCurrentThreadId() << " get\t"; if (num == 0) { cout << "failed" << endl; ReleaseSemaphore(mutex, 1, NULL); return false; } *p = cells[head]; head = (head + 1) % buffer_size; num--; cout << "ok(" << *p << ")" << endl; ReleaseSemaphore(mutex, 1, NULL); ReleaseSemaphore(semaphore_white_cell, 1, NULL); return true; } void test() { Buffer b; int i; for (i = 0; i < 7; i++) { bool ok = b.put(i); if (!ok) cout << "err: " << i << endl; } cout << "=========================\n"; int y; b.get(&y); b.get(&y); cout << "=========================\n"; for (i = 0; i < 7; i++) { int x; bool ok = b.get(&x); if (!ok) cout << "err: " << i << endl; } }
时间: 2024-04-25 17:27:34 浏览: 10
这段代码是一个使用信号量实现的缓冲区类Buffer。它具有put和get两个方法,分别用于往缓冲区中放入数据和从缓冲区中获取数据。在构造函数中,创建了三个信号量和一个互斥量。在put方法中,首先使用WaitForSingleObject函数等待semaphore_white_cell信号量,确保缓冲区中有空的单元格可以放入数据。然后使用mutex互斥量保证缓冲区的读写操作不会冲突。如果缓冲区已满,则放入数据失败,返回false;否则将数据放入缓冲区,并更新缓冲区的状态。最后释放mutex互斥量和semaphore_black_cell信号量,返回true。在get方法中,首先使用WaitForSingleObject函数等待semaphore_black_cell信号量,确保缓冲区中有数据可供获取。然后使用mutex互斥量保证缓冲区的读写操作不会冲突。如果缓冲区为空,则获取数据失败,返回false;否则获取数据并更新缓冲区的状态。最后释放mutex互斥量和semaphore_white_cell信号量,返回true。在test方法中,首先创建一个Buffer对象,然后往其中放入数据,接着从其中获取数据。最后再次从其中获取数据。
相关问题
Buffer() { num = 0; head = 0; tail = 0; mutex = CreateSemaphore(NULL, 1, 1, NULL); semaphore_white_cell = CreateSemaphore(NULL, buffer_size, buffer_size, NULL); semaphore_black_cell = CreateSemaphore(NULL, 0, buffer_size, NULL); }
这段代码看起来像是一个缓冲区的实现,使用了信号量来控制缓冲区的读写操作。具体来说,这个缓冲区有固定大小(buffer_size),并且有两个信号量来控制缓冲区中空的(semaphore_white_cell)和满的(semaphore_black_cell)单元格数量。在构造函数中,还创建了一个互斥量(mutex),用于保护缓冲区的读写操作。这个缓冲区具体的功能和实现需要看更多的代码才能确定。
def argwhereHead(head, tail, rel, array, tripleDict): wrongAnswer = 0 for num in array: if num == head: return wrongAnswer elif (num, tail, rel) in tripleDict: continue else: wrongAnswer += 1 return wrongAnswer
A:这段代码看起来是一个函数,它的作用是判断给定的头实体(head)在一个三元组数组(array)中的索引位置是否正确。如果头实体在数组中的第wrongAnswer个位置,则返回wrongAnswer,如果数组中不存在关系为(rel)和尾实体(tail)的三元组,则继续向下循环,如果没有找到正确的位置,则返回1。三元组字典(tripleDict)用于判断给定的关系和尾实体是否在三元组数组中存在。