简体   繁体   中英

How to change execution order of two threads on the basis of odd or even number in C?

I have two threads thread1 , thread2 with routines func1 , func2 respectively . Now, on the basis of a variable cnt i want to change the execution order of these two threads. That is, if cnt is even then execute func1 then func2 else if cnt is odd then execute func2 then func1 .I have to do it when cnt is from 1 to 100.

I have to achieve through the use of semaphores only. I have attempted to solve it using following code. But the code is not good enough.

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>

int cnt=1;
sem_t e_lock,o_lock;

void* func1()
{
  while(cnt<=100)
   {
    if(cnt%2==0)        //if even exec then p1
    {
        printf("value of count: %d\n",cnt);
        sem_wait(&e_lock);
        printf("even execution, process 1 first\n");
    }else 
    {
        sem_post(&o_lock);
        printf("odd execution, process 1 second\n");
        cnt++;
    }
  }
}

void* func2()
{
  while(cnt<=100)
  {
    if(cnt%2!=0)        //if odd exec then p1
    {
        printf("value of count: %d\n",cnt);
        sem_wait(&o_lock);
        printf("odd execution, process 2 first\n");
    }else 
    {
        sem_post(&e_lock);
        printf("even execution, process 2 second\n");
        cnt++;
    }
  }
}
 void main()
  {

     pthread_t thread1,thread2;

     pthread_create(&thread1,NULL,func1,NULL);
     pthread_create(&thread2,NULL,func2,NULL);

     pthread_join(thread1,NULL);
     pthread_join(thread2,NULL);
  }

Please explain the changes.

You forgot to declare the shared variable cnt as volatile :

volatile int cnt=1;

Without volatile , the compiler was allowed to generate code where the variable value is held in a register, and changes by the other thread might not be seen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM