printing odd and even number printing alternately using threads in C++

前端 未结 10 1094
后悔当初
后悔当初 2021-01-03 02:09

Odd even number printing using thread I came across this question and wanted to discuss solution in C++ . What I can think of using 2 binary semaphores odd and even semapho

10条回答
  •  执笔经年
    2021-01-03 02:49

    Please see below working code (VS2005)

    #include 
    #include 
    
    #include 
    #include 
    
    #define MAX 100
    int shared_value = 0;
    
    CRITICAL_SECTION cs;
    
    unsigned _stdcall even_thread_cs(void *p)
    {
    
        for( int i = 0 ; i < MAX ; i++ )
        {
            EnterCriticalSection(&cs);
    
            if( shared_value % 2 == 0 )
            {
                printf("\n%d", i);
            }
    
    
            LeaveCriticalSection(&cs);
    
        }
        return 0;
    }
    
    unsigned _stdcall odd_thread_cs(void *p)
    {
        for( int i = 0 ; i < MAX ; i++ )
        {
            EnterCriticalSection(&cs);
    
            if( shared_value % 2 != 0 )
            {
                printf("\n%d", i);
            }
    
            LeaveCriticalSection(&cs);  
    
        }
    
        return 0;
    }
    
    
    int main(int argc, char* argv[])
    {
         InitializeCriticalSection(&cs);
    
        _beginthreadex(NULL, NULL, even_thread_cs, 0,0, 0);
        _beginthreadex(NULL, NULL, odd_thread_cs, 0,0, 0);
    
        getchar();
        return 0;
    }
    

    Here, using shared variable shared_value, we are synchronizing the even_thread_cs and odd_thread_cs. Note that sleep is not used.

提交回复
热议问题