多线程同步问题
来源:互联网 发布:迅龙数据恢复官网 编辑:程序博客网 时间: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);
}
- MFC多线程同步问题
- 多线程同步问题
- 多线程的同步问题
- java多线程同步问题
- 关于多线程同步问题
- jsp多线程同步问题
- 多线程同步死锁问题
- servlet 多线程同步问题
- 多线程同步问题
- Servlet多线程同步问题
- VC多线程同步问题
- 初识多线程同步问题
- 多线程同步问题
- windows多线程同步问题
- 多线程同步问题
- IOS多线程同步问题
- 多线程同步问题
- 多线程-线程同步问题
- assert() 函数用法
- SOA设计模式--基本概念及原则
- C++/CLI基本数据类型探索[组图]
- VC2005:无法执行添加/移除操作,因为代码元素DlgXXX是只读的
- Struts2参数接受的问题
- 多线程同步问题
- 项目驱动学习大法
- 做有效沟通的管理者
- [转]JAVA面试题1
- Solaris下安装部署tomcat
- PHP开发环境搭建
- 最后一版支持VC6的SDK的下载地址
- 线程终结方式
- Flash社交游戏开发攻略连载(一)