- 论坛徽章:
- 0
|
- #include <unistd.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <string.h>
- #include <errno.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #define THREAD_NUM (4)
- #define FILE_NUM THREAD_NUM
- struct _thread_pipe
- {
- int w_pipe;
- int r_pipe;
- // int file_fd;
- }thread_pipe[THREAD_NUM];
- struct _thread_data
- {
- pthread_t thid;
- int *filefds;
- void *data;
- int seq;
- };
- char *file_name[] = {"./A", "./B", "./C", "./D"};
- void *thread_write(void *param)
- {
- struct _thread_data *thdata = (struct _thread_data *)param;
- int i = 0;
- char c = 0;
-
- for (i = 0; i <= thdata->seq; ++i)
- {
- int nlen = strlen((char *)thdata->data);
- if (write(thdata->filefds[i], (char *)thdata->data, nlen) != nlen)
- {
- fprintf(stderr, "write error: %s\n", strerror(errno) );
- pthread_exit( (void *)-1);
- }
- }
-
- if (thdata->seq == (FILE_NUM-1) ) /* last thread write complete */
- {
- c = 1;
- write(thread_pipe[THREAD_NUM-1].w_pipe, &c, 1);
- }
-
- while (1)
- {
- read(thread_pipe[thdata->seq].r_pipe, &c, 1);
-
- for (i = 0; i < FILE_NUM; ++i)
- {
- size_t nlen = strlen(thdata->data);
- write(thdata->filefds[i], thdata->data, nlen);
- }
-
- c = ( ( (c+1)%4)? (c+1) : 1);
- write(thread_pipe[thdata->seq].w_pipe, &c, 1);
- }
-
- pthread_exit(0);
- }
- int main(void)
- {
- int i = 0;
- int pipe_fds[THREAD_NUM][2];
- struct _thread_data thread_data[THREAD_NUM];
- char *wdata[] = {"1", "2", "3", "4"};
- int fds[FILE_NUM];
-
- /* create pipe */
- for (i = 0; i < THREAD_NUM; ++i)
- {
- if (pipe(pipe_fds[i]) < 0)
- {
- fprintf(stderr, "pipe error: %s\n", strerror(errno));
- exit(-1);
- }
- }
-
- for (i = 0; i < THREAD_NUM; ++i)
- {
- thread_pipe[i].w_pipe = pipe_fds[i][1];
- thread_pipe[(i+1)%THREAD_NUM].r_pipe = pipe_fds[i][0];
- }
-
- for (i = 0; i < FILE_NUM; ++i)
- {
- if ( (fds[i] = open(file_name[i], O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU)) < 0)
- {
- fprintf(stderr, "open error: %s\n", strerror(errno));
- exit(-1);
- }
- }
-
- for (i = 0; i < THREAD_NUM; ++i)
- {
- thread_data[i].data = wdata[i];
- thread_data[i].seq = i;
- thread_data[i].filefds = fds;
- pthread_create(&(thread_data[i].thid), NULL, thread_write, &thread_data[i]);
- }
-
- /* wait for thread to terminate */
- for (i = 0; i < THREAD_NUM; ++i)
- {
- pthread_join(thread_data[i].thid, NULL);
- }
-
- /* close all opened files or devices */
-
- return 0;
- }
复制代码 |
|