#!/usr/bin/python -i

"""demonstration of a race condition in the libraries

This is a script that shows a race condition in one of the
libraries:

The script sets a listener on a socket, and then connects to the
socket and feeds strings into it. When the strings are read out,
they're printed. The race-symptom is that, some times, some of the
strings appear to be received twice.

There are a couple of hints that I left in while I was undoing my solution.
"""

import user

from dp2.corpora import *

from pprint import pprint

def display_outbound(corpus):
    print 'OBC', corpus
    pprint(vars(corpus))

def display_inbound(corpus):
    print 'IBC', corpus
    pprint(vars(corpus))

import sys
if len(sys.argv) == 3:
    program, host, port = sys.argv
    port = int(port)
else:
    host = 'localhost'
    port = 1234

from dp2.tcp import ghost as tcp
from dp2.f0 import encode as frame, decode as unframe
l = Listen(actor=Path(unframe, display_inbound), target=Path(tcp, ('', port)))

import thread; from dp2.dispatch import schedule
thread.start_new_thread(schedule.loop, ())

schedule(l)

import time; time.sleep(2)

schedule(Presentation(actor=display_outbound, object='foo',
                      target=Path(frame, tcp, (host, port))))
schedule(Presentation(actor=display_outbound, object='bar',
                      target=Path(frame, tcp, (host, port))))
schedule(Presentation(actor=display_outbound, object='baz',
                      target=Path(frame, tcp, (host, port))))
