How to use pipe() in multiple threads?

Hi,

I have a program that runs two threads in stead of two processes. I want to use pipe to redirect the output of the first thread to the input of the second thread.

One thread is continuously writing to a pipe, and the other thread will read from the pipe.

How do I do that?

Is there any examples for piping between two threads?

Can anyone post any examples of piping between two threads?

Thanks a lot!

There should be no difference at all between piping between two threads or two processes.

The important thing about pipes, no matter how they're connected, is to use each as a one-way-conduit, despite its ability to be two-way. That way you avoid synchronization problems. In your question, it sounds like the direction of data flow is one directional, which means that one pipe should do the trick.

What is it about threads that is making you think there is anything unusual going on? Can you maybe phrase your question more specifically?

example is blow :

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>

int fd[2];

void open_pipe(void)
{
/*
** Notice here .It is the same as pipe()
*/
if(socketpair(PF_UNIX,SOCK_STREAM,0,fd) < 0)
{
fprintf(stderr,"File : %s , Line : %d , socketpair error:",
__FILE__,
__LINE__);
perror("");
abort();
}
}

void *do_task(void *arg)
{
int n;

printf\("\\t come into thread \\n"\);

n = read\(fd[0],\(void *\) &iValue,sizeof\(iValue\)\);
printf\("\\t child1 ,Line = %d \\n", iValue\);

return \(void *\) NULL;

}

void main(void)
{
int iRetSts,iValue;
pthread_t iThreadId;
pthread_attr_t vThreadAttr;

open_pipe\(\);

pthread\_attr_init\(&vThreadAttr\);
pthread\_create\(&iThreadId,NULL,do_task,\(void *\)NULL\);

iRetSts = write\(fd[1],\(void *\) &iValue,sizeof\(iValue\)\);
if\(iRetSts == -1\)
\{
    fprintf\(stderr,"File : %s , Line : %d , write failed \\n",
            \_\_FILE__,
            \_\_LINE__\);
    perror\(""\);
\} 

}

please refer to manpage of socketpair() function