Subhajit Kundu
Subhajit Kundu

Reputation: 403

Predefined order of executing threads

There are 10 functions, say, Function_1 (that prints 1 and exits), Function_2 (that prints 2 and exits), and so on till Function_10 (that prints 10 and exits).

A main function forks 10 threads, T1 to T10. T1 calls Function_1, T2 calls Function_2, and so on till T10 calls Function_10.

When I execute the main function, I expect output as 1 2 3 4 ... 10.

How can I achieve this?

Upvotes: 0

Views: 22

Answers (1)

mevets
mevets

Reputation: 10445

You need to establish what amounts to a protocol between T0 (main) and each of T{1..10}. That protocol could look like (T0 sends Print to Tn; Tn sends Printed to T0). If you don't have message passing (which would make life easy; look at golang if interested), you can simulate it crudely with condition variables. Make a structure that looks like:

struct ToDo {
     enum { Print, Printed} Op;
     int Id;
     condvar_t cv;
     mutex_t   lock;
};

And each thread then becomes:

void *Proc(int Id, struct ToDo *Next) {
      lock(&Next->lock);
      while (Next->Id != Id) {
           condvar_wait(&Next->cv, &Next->lock);
      }
      assert(Next->Op == Print);
      printf("%d\n", Id);
      Next->Op = Printed;
      Next->Id = 0;
      condvar_signal(&Next->cv);
      unlock(&Next->lock);
      ....
}

And finally your program

main() { struct ToDo Next; ... /* create condvar, lock / lock(&Next.lock); Next.Id = 0; / Create threads and pass structure */ int i;

  for (i = 1; i < 10; i++) {
       Next.Id = i;
       Next.Op = Print;
       condvar_signal(&Next.condvar);
       while (Next.Id != 0) {
            condvar_wait(&Next.condvar, &Next.lock);
       }
       assert(Next.Op == Printed);
  }

  ... /* join threads */
  exit(0);

}

Upvotes: 1

Related Questions