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); }
时间: 2024-04-25 20:27:34 浏览: 7
这段代码看起来像是一个缓冲区的实现,使用了信号量来控制缓冲区的读写操作。具体来说,这个缓冲区有固定大小(buffer_size),并且有两个信号量来控制缓冲区中空的(semaphore_white_cell)和满的(semaphore_black_cell)单元格数量。在构造函数中,还创建了一个互斥量(mutex),用于保护缓冲区的读写操作。这个缓冲区具体的功能和实现需要看更多的代码才能确定。
相关问题
struct node *head=NULL,*tail=NULL,p=NULL;
This code is not valid in C.
The "*" symbol is not used correctly.
Here is a corrected version:
```
struct node *head=NULL,*tail=NULL,*p=NULL;
```
This code declares three pointers to a struct node: head, tail, and p. All three pointers are initialized to NULL.
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; } }
这段代码是一个使用信号量实现的缓冲区类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对象,然后往其中放入数据,接着从其中获取数据。最后再次从其中获取数据。