Sasha
Sasha

Reputation:

How can I pass data from a thread to the parent process?

I have a main process that uses a single thread library and I can only the library functions from the main process. I have a thread spawned by the parent process that puts info it receives from the network into a queue.

I need to able to tell the main process that something is on the queue. Then it can access the queue and process the objects. The thread cannot process those objects because the library can only be called by one process.

I guess I need to use pipes and signals. I also read from various newsgroups that I need to use a 'self-trick' pipe.

How should this scenario be implemented?

A more specific case of the following post:

How can unix pipes be used between main process and thread?

Upvotes: 1

Views: 2292

Answers (3)

Tobias
Tobias

Reputation: 6507

The "optimal" solution depends quite a bit on your concrete setup. Do you have one process with a main thread and a child thread or do you have one parent process and a child process? Which OS and which thread library do you use?

The reason for the last question is that the current C++03 standard has no notion of a 'thread'. This means in particular that whatever solution your OS and your thread library offer are platform specific. The most portable solutions will only hide these specifics from you in their implementation.

In particular, C++ has no notion of threads in its memory model, nor does it have a notion of atomic operations, synchronization, ordered memory accesses, race conditions etc.

Chances are, however, that whatever library you are using already provides a solution for your problem on your platform.

Upvotes: 0

Bastien Léonard
Bastien Léonard

Reputation: 61743

Why not use a simple FIFO (named pipe)? The main process will automatically block until it can read something.
If it shouldn't block, it must be possible to poll instead, but maybe it will suck CPU. There probably exists an efficient library for this purpose.

I wouldn't recommend using signals because they are easy to get wrong. If you want to use them anyway, the easiest way I've found is:

  • Mask all signals in every thread,
  • A special thread handles signals with sigwait(). It may have to wake up another thread which will handle the signal, e.g. using condition variables.

The advantage is that you don't have to worry anymore about which function is safe to call from the handler.

Upvotes: 2

Benoît
Benoît

Reputation: 16994

I highly suggest you used a thread-safe queue such as this one (article and source code). I have personally used it and it's very simple to use. The API consist in simple methods such as push(), try_pop(), wait_and_pop() and empty().

Note that it is based on Boost.Thread.

Upvotes: -1

Related Questions