标签:
转自网络
1 多线程同步
bool Thread::stop()
{
QMutexLocker locker(&mutex);
m_stop = true;
return m_stop;
}
MyData data; QReadWriteLock lock; void ReaderThread::run() { ... lock.lockForRead(); access_data_without_modifying_it(&data); lock.unlock(); ... } void WriterThread::run() { ... lock.lockForWrite(); modify_data(&data); lock.unlock(); ... }
QSemphore
const int DataSize = 100000;
const int BufferSize = 4096;
char buffer[BufferSize];
QSemaphore freeSpace(BufferSize);
QSemaphore usedSpace(0);
void Producer::run() { for (int i = 0; i < DataSize; ++i) { freeSpace.acquire(); buffer[i % BufferSize] = "MING"[uint(rand()) % 4]; usedSpace.release(); } }
在生产者中,我们从获取一个“自由的”字节开始。如果缓存被消费者还没有读取的数据填满,acquire()的调用就会阻塞,直到消费者已经开始消耗这些数据为止。一旦我们已经获取了这个字节,我们就用一些随机数据("M"、"I"、"N"或"G")填充它并且把这个字节释放为“使用的”,所以它可以被消费者线程使用。
void Consumer::run() { for (int i = 0; i < DataSize; ++i) { usedSpace.acquire(); cerr << buffer[i % BufferSize]; freeSpace.release(); } cerr << endl; }
int main() { Producer producer; Consumer consumer; producer.start(); consumer.start(); producer.wait(); consumer.wait(); return 0; }
const int DataSize = 100000;
const int BufferSize = 4096;
char buffer[BufferSize];
QWaitCondition bufferIsNotFull;
QWaitCondition bufferIsNotEmpty;
QMutex mutex;
int usedSpace = 0;
在缓存之外,我们声明了两个QWaitCondition、一个QMutex和一个存储了在缓存中有多少个“使用的”字节的变量。
void Producer::run() { for (int i = 0; i < DataSize; ++i) { mutex.lock(); if (usedSpace == BufferSize) bufferIsNotFull.wait(&mutex); buffer[i % BufferSize] = "MING"[uint(rand()) % 4]; ++usedSpace; bufferIsNotEmpty.wakeAll(); mutex.unlock(); } }
bool wait ( QMutex * mutex, unsigned long time = ULONG_MAX );
void Consumer::run() { forever { mutex.lock(); if (usedSpace == 0) bufferIsNotEmpty.wait(&mutex); cerr << buffer[i % BufferSize]; --usedSpace; bufferIsNotFull.wakeAll(); mutex.unlock(); } cerr << endl; }
标签:
原文地址:http://www.cnblogs.com/laien/p/5540719.html