[SOLVED] QSemaphore example: different behavior when splitting program over multiple files???



  • I am studying threading in Qt by reading the Threading chapter in 'C++ GUI Programming with Qt 4'. When I build and run the semaphore example (available as a single file online at https://github.com/BartVandewoestyne/Cpp-GUI-Programming-with-Qt-4/tree/master/2nd_edition/examples/chap14/semaphores_original) it gives me the correct behavior:

    Run 1: PPPPccccPPPPccccPPcc
    Run 2: PPPPccPPccccPPPPcccc
    Run 3: PPPPccccPPPPccccPPcc

    I tried to split up the single file into several .h and .cpp files, see https://github.com/BartVandewoestyne/Cpp-GUI-Programming-with-Qt-4/tree/master/2nd_edition/examples/chap14/semaphores When I now build and run my version of this semaphore example, I get the following incorrect output:

    PPPccccccccccP

    and the program seems to be in a deadlock state. The above input is incorrect, because if the producer (P) has only written 3 times, then the consumer (c) cannot read 10 things, but only maximum 3.

    I am wondering what is wrong with my version of the program. My educated guess is that it has something to do with the variables declared and initialized in globals.h and globals.cpp. Adding the extern keyword was the best solution I could come up with for these global variables.

    Anything that can help me gain insight into what's happening here, or even a clean fix, is highly appreciated!



  • Hi,

    in the splitted Consumer code you use always the same semaphore

    // non splitted
    void Consumer::run()
    {
        for (int i = 0; i < DataSize; ++i) {
            usedSpace.acquire();
            //std::cerr << buffer[i % BufferSize];
    	std::cerr << "c";
            freeSpace.release();
        }
        std::cerr << std::endl;
    }
    

    and the splitted version is

    // consumer.cpp
    void Consumer::run()
    {
        for (int i = 0; i < DataSize; ++i) {
            freeSpace.acquire(); // <------ shoud be usedSpace
    	//std::cerr << buffer[i % BufferSize];
    	std::cerr << "c";
    	freeSpace.release();  
        }
        std::cerr << std::endl;
    }


  • Thanks! Stupid of me that I overlooked this typo :-(



  • You're Welcome


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.