1

I have an application that creates two threads. (thread_1 for a Qt GUI and thread_2 for an app that runs a TCL interpreter).

I want thread_1 (Qt GUI) to create a command and send it to thread_2 (TCL interpreter).

I'm thinking of connecting thread_1's stdout to thread_2's stdin, and I don't know how to do it ? if you know how to do it or can suggest different way of work, I'd appreciate your help.

László Papp
  • 51,870
  • 39
  • 111
  • 135
  • hmm, if you have *threads*, you don't need them to communicate through the system: just set up a pair of `std::list` with synchronisation for bidirectional messaging. – didierc Jun 03 '14 at 15:40
  • I'm new to that, can you give an example or a link to where I can learn more about this ? – user3514268 Jun 03 '14 at 16:03
  • http://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/ that's for the message queue. – didierc Jun 03 '14 at 16:23
  • It sounds like your real question is, "how do I communicate between threads". The short answer is that you can use any collection you like (list, queue, map, array) so long as you use an appropriate synchronization mechanism (lock, mutex, semaphore) to prevent concurrent, conflicting accesses to the collection. – David Schwartz Jun 03 '14 at 16:31
  • _"...for an app that runs a TCL interpreter"_ Are you sure these are two threads in the same process? Because I wouldn't usually describe one thread inside a process as an "app". – Useless Jun 03 '14 at 17:46
  • Why do you want to use threads at all? – Donal Fellows Jun 04 '14 at 08:21

2 Answers2

1

The solution I propose requires to set up 2 std::queue<> or std::list to let each thread pass a message to the other one and vice versa. The simplest way is to have each thread setup its own incoming message queue, and let other threads get a pointer to it. First you need a synchronized version of the queue datatype: as I gave in the comment, there's an implementation there.

Then you only need to upgrade your thread class (or runnable class, or whatever you're using as an abstraction of a task) with one such queue available internally, and a send method publicly accessible so that other tasks may post a message to it. Your task will then have to periodically check that queue for incoming message, and eventually process it.

NB: I got that page from stack overflow itself, since the blog owner is a member of this community. See that page talking about queue synchronization issue.

Community
  • 1
  • 1
didierc
  • 14,572
  • 3
  • 32
  • 52
0

I am not sure why you would like to go through standard input and output here, but I think the issue might be much simpler than you think. I would just personally use the qt signal-slot mechanism as follows:

connect(guiThreadSender, SIGNAL(sendCommand(const QByteArray&)),
        tclThreadReceiver, SLOT(handleCommand(const QByteArray&)));
László Papp
  • 51,870
  • 39
  • 111
  • 135