多线程同步问题

来源:互联网 发布:迅龙数据恢复官网 编辑:程序博客网 时间:2024/06/04 19:21

有四个线程1,2,3,4,线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........
现在有四个文件.ABCD.初始都为空.
现要让四个文件呈如下格式:
A:  1 2 3 4 1 2....
B:  2 3 4 1 2 3....
C:  3 4 1 2 3 4....
D:  4 1 2 3 4 1....

设计程序.

 

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

typedef struct file_node{
        int             r_pipe;
        int             w_pipe;
        int             fd;
}file_node;

char *file[] = {"./a","./b","./c","./d"};

file_node  node_list[4];

void *thread_func(void *arg);

int main()
{
        int     *num, i;
        int     sockpair[2];

        memset(node_list, 0, sizeof(node_list));

       //打开文件,构建线程间管道

        for (i=0; i<4; i++) {

                if (socketpair(AF_UNIX,SOCK_STREAM, 0, sockpair)) {
                        printf("socketpair error !/n");
                        exit(1);
                }

                node_list[i].w_pipe = sockpair[0];

                if (i != 3)
                        node_list[i+1].r_pipe = sockpair[1];
                else
                        node_list[0].r_pipe = sockpair[1];

                node_list[i].fd = open(file[i], O_CREAT | O_WRONLY| O_APPEND, S_IRUSR|S_IWUSR);
                if (node_list[i].fd < 0) {
                        printf("open fd error , exit !/n");
                        exit(1);
                }
        }
       //创建线程      

        for(i=0;i<4; i++) {
                num =(int*)malloc(sizeof(int));
                *num = i;
                pthread_create(NULL, NULL, thread_func, num);
        }

        pause();
}

void *thread_func(void *arg)
{
        pthread_t          pid;
        char               buf[100];
        int                w_fd, num;

        num = *(int*)arg;
        free(arg);
        pid = pthread_self();
        pthread_detach(pid);

        sprintf(buf, "%d", num+1);
        w_fd = node_list[num].fd;


        for (; ; )
        {
                //写文件

                if (write(w_fd, (void*)buf, strlen(buf)) != strlen(buf)) {
                        printf("write something to file error !/n");
                        break;
                }
                //通知下一个线程写      

                if (write(node_list[num].w_pipe, (void*)&w_fd, sizeof(int)) != sizeof(int)) {
                        printf("write fd to pipe error !/n");
                        break;
                }
                if (read(node_list[num].r_pipe, &w_fd, sizeof(int)) != sizeof(int)) {
                        printf("read fd from pipe error !/n");
                        break;
                }
        }

        pthread_exit(0);
}

原创粉丝点击