When interviewing for a job in the past, I was asked the following question:

Write a multithreaded program that prints a sequence of characters like this: A, B, A, B, A, B… Synchronize properly so it never prints the same character more than once in a row.

Thinking quickly on my feet 🙂 I realized the trick is to use an event object (I will be using this one). But wait, one event object is not enough. The real trick is to use two event objects! Where thread 1 waits on event 1 to be signaled, then prints ‘A’, and finally signals event 2; and repeats the sequence in a loop. Thread 2 waits on event 2, then prints ‘B’, and finally signals event 1. Ditto loop. That should do it!

The answer:

A
B
A
B
A
B

Program output.

6 Replies to “Interview question, part 1”

  1. Hmm, it does not say which thread should print what…
    A multithreaded program has at least two threads, right?
    The following should work:

    void print()
    {
    for (;;)
    {
    std::cout << ‘A’ << std::endl;
    std::cout << ‘B’ << std::endl;
    }
    }

    int main()
    {
    std::thread t1(print);
    t1.join();
    return 0;
    }

    // 😀

Leave a Reply to Martin VorbrodtCancel reply