Introduction to QT thread synchronization instances (3)

Source: Internet
Author: User

 

Http://mobile.51cto.com/symbian-272643_2.htm


    For this instance, each byte is regarded as a resource. In actual applications, operations are usually performed on a larger unit to reduce the overhead caused by the use of semaphores.

     
     
    1. void Producer::run()  
    2. {  
    3.     for (int i = 0; i < DataSize; ++i) {  
    4.         freeSpace.acquire();  
    5.         buffer[i % BufferSize] = "MING"[uint(rand()) % 4];  
    6.         usedSpace.release();  
    7.     }  

    In the producer, we start from getting a "free" byte. If the cache is filled with data that the consumer has not read, acquire () calls will be blocked until the consumer has begun to consume the data. Once we have obtained this byte, we use some random data ("M", "I", "n", or "G ") fill it and release this Byte as "used", so it can be consumed by the consumerThread.

     
     
    1. void Consumer::run()  
    2. {  
    3.     for (int i = 0; i < DataSize; ++i) {  
    4.         usedSpace.acquire();  
    5.         cerr << buffer[i % BufferSize];  
    6.         freeSpace.release();  
    7.     }  
    8.     cerr << endl;  

    In the consumer, we start from obtaining a "used" byte. If the cache does not contain any readable data, the acquire () call will be blocked until the producer has produced some data. Once we have obtained this byte, we print it and release it as "free" so that it can be used by the producer to refill the data.

     
     
    1. int main()  
    2. {  
    3.     Producer producer;  
    4.     Consumer consumer;  
    5.     producer.start();  
    6.     consumer.start();  
    7.     producer.wait();  
    8.     consumer.wait();  
    9.     return 0;  

    The main () function has simple functions and is responsible for starting producers and consumers.ThreadAnd then automatically exit after their respective execution is complete.

    Qwaitcondition

    Another solution to the producer and consumer problems is to use qwaitcondition, which allowsThread inWake up others under certain conditionsThread. The wakeone () function randomly wakes up a wait when the condition is met.ThreadWhile the wakeall () function wakes up all waits when conditions are met.Thread.
    The following rewrite producer and consumer instances, with qmutex as the waiting condition, qwaitcondition allowsThreadWake up others under certain conditionsThread.

     
     
    1. const int DataSize = 100000;  
    2. const int BufferSize = 4096;  
    3. char buffer[BufferSize];  
    4. QWaitCondition bufferIsNotFull;  
    5. QWaitCondition bufferIsNotEmpty;  
    6. QMutex mutex;  
    7. int usedSpace = 0; 

    Besides the cache, we declare two qwaitcondition, one qmutex, and one variable that stores the number of "used" bytes in the cache.

     
     
    1. void Producer::run()  
    2. {  
    3.     for (int i = 0; i < DataSize; ++i) {  
    4.         mutex.lock();  
    5.         if (usedSpace == BufferSize)  
    6.             bufferIsNotFull.wait(&mutex);  
    7.         buffer[i % BufferSize] = "MING"[uint(rand()) % 4];  
    8.         ++usedSpace;  
    9.         bufferIsNotEmpty.wakeAll();  
    10.         mutex.unlock();  
    11.     }  

    In the producer, we start by checking whether the cache is full. If it is full, we wait for the "cache is not full" condition. When this condition is met, we write a byte to the cache, add usedspace, and wake up any waiting for this "cache is not blank" condition to become true.Thread.

    All statements in the for loop need to be protected by mutex to protect the atomicity of their operations.

     
     
    1. bool wait ( QMutex * mutex, unsigned long time = ULONG_MAX ); 

    This function will unlock and wait for the mutex. It has two parameters: the first parameter is a locked mutex, and the second parameter is the waiting time. If the mutex used as the first parameter is locked or recursive, the wait () function returns immediately.

    Which calls the wait () OperationThreadThe mutex used as a parameter changes to the locked status before the call, and then the self-blocking status changes to the waiting status until the following conditions are met:

    OthersThreadThe wakeone () or wakeall () function is called. In this case, the "true" value is returned.

    The second parameter time-out (in milliseconds). The default value of this parameter is ulong_max, indicating that the parameter never times out. In this case, "false" is returned.

    Before the wait () function returns, it will reset the mutex parameter to the locked State to ensure the principle conversion from the locked state to the waiting state.

     
     
    1. void Consumer::run()  
    2. {  
    3.     forever {  
    4.         mutex.lock();  
    5.         if (usedSpace == 0)  
    6.             bufferIsNotEmpty.wait(&mutex);  
    7.         cerr << buffer[i % BufferSize];  
    8.         --usedSpace;  
    9.         bufferIsNotFull.wakeAll();  
    10.         mutex.unlock();  
    11.     }  
    12.     cerr << endl;  

    The consumer is opposite to the producer. The consumer waits for the "cache is not blank" condition and wakes up any "cache is not full" condition.Thread.

    The main () function is basically the same as the above.

    The static function currentthread () in the qthread class can return the currentThreadOfThreadId. In the X11 environment, this ID is an unsigned long value.

    Summary: AboutQt Thread SynchronizationI hope this article will help you with the introduction of the instance.

     

     

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.