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

前端 未结 10 1154
后悔当初
后悔当初 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 03:05

    This is the easiest solution you can refer:

    #include
    #include
    #include
    #include
    int count=0;
    using namespace std;
    mutex m;
    void* printEven(void *a)
    {
       while(1)
       {
           m.lock();
           if(count%2==0)
           {
              cout<<" I am Even"<100)
              break;
           m.unlock();
        }
     }
     int main()
     {
         int *ptr = new int();
         pthread_t thread1, thread2;
         pthread_attr_t attr;
         pthread_attr_init(&attr);
         pthread_create(&thread1,&attr,&printEven,NULL);
         pthread_create(&thread2,&attr,&printOdd, NULL);
         pthread_join(thread1,&ptr);
         pthread_join(thread2,&ptr);
         delete ptr;
     }
    

提交回复
热议问题