The following program is a version of the alternating execution using two mailboxes. The main program creates two threads and forces them to run in an alternating way. More precisely, if the threads are A and B, this program forces them to execute in an order of A, B, A, B, A, B, ....
Click here to download a copy of this program.
#include <stdio.h>
#include <thread.h>
#include <synch.h>
#include "mbox.h"
mbox_t To_A, To_B;
int Max_Run;
void *ThreadA(void *JunkPTR)
{
int i, Data;
printf("Thread A started\n");
for (i = 1; i <= Max_Run; i++) {
thr_yield();
msg_receive(&To_A, &Data);
printf("This is from thread A\n");
msg_send(&To_B, &i);
}
printf("Thread A ends\n");
}
void *ThreadB(void *JunkPTR)
{
int i, Data;
printf(" Thread B started\n");
for (i = 1; i <= Max_Run; i++) {
thr_yield();
msg_receive(&To_B, &Data);
printf(" This is from thread B\n");
msg_send(&To_A, &i);
}
printf("Thread B ends\n");
}
void main(int argc, char *argv[])
{
thread_t ID_A, ID_B;
size_t Status_A, Status_B;
int Data = 0;
if (argc != 2) {
printf("Use %s #-of-iterations\n", argv[0]);
exit(0);
}
Max_Run = abs(atoi(argv[1]));
printf("Parent started ...\n");
msg_init(&To_A);
msg_init(&To_B);
msg_send(&To_A, &Data);
thr_create(NULL, 0, ThreadA, (void *) NULL, 0,
(void *) &ID_A);
thr_create(NULL, 0, ThreadB, (void *) NULL, 0,
(void *) &ID_B);
thr_join(ID_A, 0, (void *) &Status_A);
thr_join(ID_B, 0, (void *) &Status_B);
printf("Parent exits ...\n");
}